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?
>Solution :
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.