请考虑以下代码:
const obj = {
a: 1,
b: 2
}
let possibleKey: string = 'a'
if (possibleKey in obj) console.log(obj[possibleKey])当possibleKey in obj为真时,我们知道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; }'.发布于 2020-01-07 12:27:46
每医生们
对于
n in x表达式,其中n是字符串文本或字符串文本类型,x是联合类型,“true”分支缩小到具有可选或必需属性n的类型,而“false”分支缩小到具有可选或缺少属性n的类型。
换句话说,n in x缩小了x,而不是n,并且只针对字符串文本类型或字符串文本类型in联合类型。要使该表达式工作,您必须向编译器提供更多信息,例如使用https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions
if (possibleKey in obj) {
console.log(obj[<keyof typeof obj>possibleKey]);
}https://stackoverflow.com/questions/59628330
复制相似问题