Typescript: limiting types in object values

一笑奈何 提交于 2021-01-28 06:06:09

问题


I'm trying to create a large object whose values are limited to only 3 types: Texture, Geometry, Script

My object would look something like this:

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
    //...
}

How can I declare the Assets interface so the value in each key-value pair is limited to these 3 types? I tried starting with:

interface Assets{
    key: Texture | Geometry | Script;
}

but then it breaks when I assign

this.assets = {sky: new Texture()}

Because it's expecting only key instead of sky. Is there any way of achieving this without nesting objects within objects?


回答1:


How about:

type Assets = {
    [key: string]: Texture | Geometry | Script;
}

That type will allow for string keys and values of one of the types you requested.

More on the subject: Indexable Types



来源:https://stackoverflow.com/questions/45644452/typescript-limiting-types-in-object-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!