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
}
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.