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

Typescript how to deal with union types and different attributes

I need to develop a function that accept 2 type of input.

type InputA = {
 name: string
 content: string
 color: string
}

type InputB = {
 name: string
 content: number
}

type Input = InputA | InputB

When I try to implement the function accepting this 2 inputs, I would like to check if the input has the color attribute, so I can distinct the 2 types.

However this will lead me to a compiler error:

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


function foo(input:Input){
 const color = (input.color) ? input.color : undefined;
                  // ^
                  // | Property 'color' does not exist on type 'Input'.
                  // | Property 'color' does not exist on type 'InputB'.
 ...
}

I know I can implement a new attribute, like type_name, that exists in both types and then check on that one. But I would like to avoid it since I don’t like having an extra attribute only for this reason in this particular function.

Is there a better way?

>Solution :

For type-safety reasons, you can’t access properties which might not exist on a union type with the dot-notation. Use the in operator instead.

function foo(input:Input){
  const color = "color" in input ? input.color : undefined
}

Playground

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