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 error where function parameter can be of type string or another type

I need help fixing a typescript error that I do not fully understand. The function accepts a single argument option that can either be a string or another object type. Below is an example screenshot from the typescript playground.

enter image description here

When I tried accessing the name prop, I expected to get it from the Details type. However, it throws an error. Why is it causing an error and how do I fix it?

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 :

I’d recommend reading the guide on Union types.

Essentially, you’re only able to access properties that exist on all types within a Union type. string does not have a name property, so option.name doesn’t make any sense if the option is a string, and the compiler won’t allow that because **you haven’t proven if it’s a string or a Details object`

You could do something like this:

if(typeof option !== "string") {
  console.log(option.name)
}

Because in that case, the compiler can infer that Option is a Details.

You can also use type guards to check if something is a certain type.

tl;dr; read the link at the start of this answer (this one) about Union types, and go from there.

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