简体   繁体   English

TypeScript:为什么我不能访问仅在一个 object 上定义的联合类型的属性?

[英]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.

相关问题 为什么我不能将打字稿泛型类型分配给该类型的联合? - Why can't I assign a typescript generic type to a union of that type? 为什么不能访问对象的属性? - Why can't I access the property of the object? 为什么我不能使用评估为相同字符串的不同类型访问对象属性? - Why can I not access an object property using a a different type which evaluates to the same string? 为什么不能枚举定义为不可枚举的对象属性? - Why can't I enumerate object property defined as not enumerable? 打字稿获取属性仅在联合之一中可用 - Typescript get property only available in one of union 为什么我只能*访问* setInterval中的对象属性? - Why can I *only* access an object property inside setInterval? 为什么我不能直接访问对象文字的属性? - Why can't I directly access a property of an object literal? 为什么我无法在javascript中访问对象的属性? - Why can't I access a property of an object in javascript? 为什么我不能在我的对象文字中访问this.property? - why can't I access this.property in my object literal? 为什么当我在此JavaScript对象上使用反射时,看不到其原型对象中定义的属性? - Why when I use reflection on this JavaScript object I can't see a property defined in its prototype object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM