问题
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