gpt4 book ai didi

typescript - 为什么 TypeScript 类型保护 'in' 不将类型缩小为 keyof 类型?

转载 作者:行者123 更新时间:2023-12-03 21:16:56 25 4
gpt4 key购买 nike

考虑这个代码:

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

最佳答案

the docs :

For a n in x expression, where n is a string literal or string literal type and x is a union type, the “true” branch narrows to types which have an optional or required property n, and the “false” branch narrows to types which have an optional or missing property n.



换句话说, n in x收窄 x ,不是 n , 并且仅适用于字符串文字或字符串文字类型 in联合类型。要使该表达式起作用,您必须向编译器提供更多信息,例如使用 type assertion :
if (possibleKey in obj) {
console.log(obj[<keyof typeof obj>possibleKey]);
}

关于typescript - 为什么 TypeScript 类型保护 'in' 不将类型缩小为 keyof 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59628330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com