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?
CodePudding user response:
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.
CodePudding user response:
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