3

I have a variable that can either be a string or object like this:

value?: string | { name: string, type: string }

Trying something below but I get a compile error:

console.log(value?.name || value)
console.log(value?.type)

How can use this variable if it can be either type?

2
  • 1st you use value and in second console you are using track? Commented Feb 16, 2022 at 0:10
  • whoops thank you, issue remains just a typo Commented Feb 16, 2022 at 0:10

2 Answers 2

5

In this case you can do:

console.log(typeof value === 'string' ? value : value?.name)

Typescript can narrow the type using type-guards, see here for more details.

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

Comments

4

So you have two options

console.log(typeof value === 'string' ? value : value.name);

But as you used ?: in definition for this value (allowing undefined) and as i think that console is only for simple example there

if (value === undefined) {
} else if (typeof value === 'string') {
} else {
}

Would be best.

This issue you found is mostly done because both values for value variable are objects and ts saw that the types are not compatible and asks you to narrow them by hand

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.