打字稿:限制对象值的类型

马奎佐

我试图创建一个大型对象,其价值仅限于3种类型:TextureGeometryScript

我的对象看起来像这样:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章