我试图创建一个大型对象,其价值仅限于3种类型:Texture
,Geometry
,Script
我的对象看起来像这样:
var assets: Assets = {
sky: <Texture>,
ground: <Texture>,
city: <Geometry>,
people: <Script>,
cars: <Script>,
sun: <Circle> // <--This should fail because it's not one of the 3 types
//...
}
如何声明Assets
接口,以便每个键值对中的值都限于这3种类型?我尝试从开始:
interface Assets{
key: Texture | Geometry | Script;
}
但是当我分配时它打破了
this.assets = {sky: new Texture()}
因为它只期待key
而不是sky
。没有在对象内嵌套对象的任何方法?
怎么样:
type Assets = {
[key: string]: Texture | Geometry | Script;
}
该类型将允许使用字符串键和所请求类型之一的值。
有关此主题的更多信息:可索引类型
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句