![](/img/trans.png)
[英]Why doesn't the TypeScript type guard narrow the type correctly when using intersection types?
[英]Why doesn't TypeScript type guard 'in' narrows types to keyof types?
考虑这个代码:
const obj = {
a: 1,
b: 2
}
let possibleKey: string = 'a'
if (possibleKey in obj) console.log(obj[possibleKey])
当possibleKey in obj
为 true 时,我们知道possibleKey
类型为keyof typeof obj
,对吗? 为什么 TypeScript 类型系统没有检测到并将string
缩小到该类型? 相反,它说:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; b: number; }'.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.