简体   繁体   中英

TypeScript: Why can't I access a property on a Union Type which is only defined on one object?

I want to have either an object with the property a which is a number or an object with property b which is a string. In plain JavaScript the variable test would be either a number or undefined if the other object has been passed. Why is this an error in TypeScript? Or is there a way to do this without an type guard?

function t(aOrB: {a:number} | {b:string}){
    const test: number | undefined = aOrB.a
}

https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhgCgIYHkBOAhALmQG8MCIwBbAIwFMcBfZAHxOoIGcYc4IBzBgEpiwZGORQkXVLS5EKNei2SQAJrRC9aq5AF5k2fADoMwBsCA

You need to do a check on if ('a' in aOrB) and if ('b' in aOrB) before returning.

you can use typeOf like this

 function t(aOrB:any){ const test =((typeof(aOrB) == "object")?aOrB.a:aOrB); console.log(test); } t({a:123}); t(123)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM