Charanor
Charanor

Reputation: 860

Nested advanced types, inferring that type is key of another object?

I have a datastructure like this:

const VALUES = {
    val1: {...},
    val2: {...},
    val3: {...}
};

const DATA = [
    {
        name: "name1",
        value: "val1" // The value here, is a KEY (not a value) in the "VALUES" object.
    },
    {
        name: "name2",
        value: "val2"
    }
];


type DataType = typeof DATA[number];/*{
    name: string;
    value: string; // I want this to be inferred as "typeof keyof VALUES"
}*/

So my question is; is there a way to hint to TypeScript that value in type DataType should have the type typeof keyof VALUES (instead of string) without having to explicitly creating the type? Something like this perhaps:

const DATA = [
    {
        name: "name1",
        value: (keyof VALUES).val1
    },
    {
        name: "name2",
        value: (keyof VALUES).val2
    }
];

Upvotes: 0

Views: 38

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

You can use type assertion:

const DATA = [{ name: "name1", value: "val1" as keyof typeof VALUES }];

But I'd rather define a type and explicitly use it for DATA variable. This way typescript will validate that values are indeed valid keys.

Upvotes: 1

Related Questions