Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combination of values in object attributes typescript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading