在Typescript中,您可以声明数组中的所有元素都具有相同的类型,如下所示:
const theArray: MyInterface[]
您是否可以做类似的事情来声明一个对象的所有属性值都必须是同一类型?(不指定每个属性名称)
例如,我目前正在这样做:
interface MyInterface {
name:string;
}
const allTheThingsCurrently = {
first: <MyInterface>{name: 'first thing name' },
second: <MyInterface>{name: 'second thing name' },
third: <MyInterface>{name: 'third thing name' },
//...
};
...请注意我必须<MyInterface>
为每个属性指定的内容。有什么捷径吗?即我在想像这样的事情...
const allTheThingsWanted:MyInterface{} = {
first: {name: 'first thing name' },
second: {name: 'second thing name' },
third: {name: 'third thing name' },
//...
};
MyInterface{}
是无效代码的一部分,我正在寻找一种方式来减少冗余,并选择额外的严格性,以防止任何其他属性添加到不同类型的对象中。
interface Thing {
name: string
}
interface ThingMap {
[thingName: string]: Thing
}
const allTheThings: ThingMap = {
first: { name: "first thing name" },
second: { name: "second thing name" },
third: { name: "third thing name" },
}
这里的缺点是您可以访问任何属性而allTheThings
不会出现任何错误:
allTheThings.nonexistent // type is Thing
通过将其定义ThingMap
为[thingName: string]: Thing | void
,可以使其更加安全,但这将要求在整个位置进行空检查,即使您正在访问的属性也是如此。
const createThings = <M extends ThingMap>(things: M) => things
const allTheThings = createThings({
first: { name: "first thing name" },
second: { name: "second thing name" },
third: { name: "third thing name" },
fourth: { oops: 'lol!' }, // error here
})
allTheThings.first
allTheThings.nonexistent // comment out "fourth" above, error here
该createThings
函数具有泛型M
,并且M
可以是任意值,只要所有值均为Thing
,就可以返回M
。当您传递对象时,它将针对后面的类型验证该对象extends
,同时返回与您传递的对象相同的形状。
这是“最智能”的解决方案,但使用看上去有些聪明的hack使其真正起作用。无论如何,在TS添加更好的模式来支持此类情况之前,这将是我的首选路线。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句