M -
M -

Reputation: 28497

Typescript: limiting types in object values

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?

Upvotes: 2

Views: 3925

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164447

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

Upvotes: 5

Related Questions