1

I was wondering if there is a construct in typescript that I can use in order to restrict possible values of an object depending on the values. I can describe it something like that:

interface IObject = {
key1:string;
key2:string;
key3:"A" | null;
key4: (if key3 is 'A' then allow 'value1' |'value2' else if it is null then allow "value3" | "value4" 
}

Does typescript support that?

1
  • Yes it almost does. The questions are almost similar, but the exact match is below Commented May 16, 2022 at 12:48

1 Answer 1

1

You can declare the type like this:

type IObject = {
  key1:string;
  key2:string;
} & ({
  key3:"A",
  key4: 'value1' |'value2'
} | {
  key3: null,
  key4: "value3" | "value4" 
})

We basically create a union of all valid key3 and key4 combinations and intersect them with the rest of the properties.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.