2

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.

2
  • 3
    Types are for compile-time checks and access enforcement. So you can say something is ObjectWithLorem | ObjectWithIpsum (one or the other), but to use it you need to narrow the type to know which property to access. Can you show more of how you want to use this? Commented May 5, 2022 at 14:52
  • This can be done with a union of tuples you can generate from a map of keys to interfaces. Commented May 5, 2022 at 15:07

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.