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.
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?
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.
Here, option can be either string or Details, so it fix this error while accessing name you need to make sure that the type of option variable isn't string.
const testFun = (option:Test['option']) => {
if (typeof option === "string") return;
console.log(option.name);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.