[英]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.我想要一个带有属性a
的 object 或一个带有属性b
的 object ,这是一个字符串。 In plain JavaScript the variable test would be either a number or undefined if the other object has been passed.在普通的 JavaScript 中,如果另一个 object 已通过,则变量 test 将是一个数字或未定义。 Why is this an error in TypeScript?为什么这是 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 https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhgCgIYHkBOAhALmQG8MCIwBbAIwFMcBfZAHxOoIGcYc4IBzBgEpiwZGORQkXVLS5EKNEi2SQAJrwkBsCAqAq
You need to do a check on if ('a' in aOrB)
and if ('b' in aOrB)
before returning.在返回之前,您需要检查if ('a' in aOrB)
和if ('b' in aOrB)
。
you can use typeOf like this你可以像这样使用typeOf
function t(aOrB:any){ const test =((typeof(aOrB) == "object")?aOrB.a:aOrB); console.log(test); } t({a:123}); t(123)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.