rwacarter
rwacarter

Reputation: 2004

Typescript: Make type dependent on value of variable

I have the following code:

interface ObjectWithLorem {
    lorem: string;
}

interface ObjectWithIpsum {
    ipsum: string;
}

type KeyName = 'lorem' | 'ipsum';

const key: KeyName = 'lorem';

type Object = key === 'lorem' ? ObjectWithLorem : ObjectWithIpsum;

const object: Object = {
    lorem: 'Lorem'
}

Playground Link

This is obviously not working, but I was wondering if there was either a way to make it work as-is, or at least an alternative solution to have the same effect - essentially the Object type should either be an ObjectWithLorem or ObjectWithIpsum interface, depending on whether the key variable is lorem or not.

Upvotes: 2

Views: 722

Answers (1)

tenshi
tenshi

Reputation: 26324

If we've got our keys and interfaces, let's map each key to the corresponding interface:

type KeyToInterfaceMap = {
    lorem: ObjectWithLorem;
    ipsum: ObjectWithIpsum;
};

Then we use a mapped type to get our possible tuples:

type PossibleTuples = {
    [K in keyof KeyToInterfaceMap]: [K, KeyToInterfaceMap[K]];
}[keyof KeyToInterfaceMap];

Now say if you've got a variable of type PossibleTuples, maybe like this:

declare const checkMe: PossibleTuples;

We can do what you want just like this:

const [key, obj] = checkMe;

if (key === "lorem") {
    obj // inferred as ObjectWithLorem
}

You can explore more with this method below:

Playground

Upvotes: 1

Related Questions