【发布时间】:2021-10-30 00:52:26
【问题描述】:
代码
const test = {
a: 'b',
c: 'd',
} as const;
const toPick: string = 'a';
if (toPick in test) {
console.log(test[toPick]); // not "b" (Error)
}
没有as const也报错
错误
元素隐含地具有“任何”类型,因为类型的表达式 'string' 不能用于索引类型
'{ readonly a: "b"; readonly c: "d"; }'。
没有找到带有“字符串”类型参数的索引签名 输入
'{ readonly a: "b"; readonly c: "d"; }'。
【问题讨论】:
-
in缩小的工作方式不是这样:typescriptlang.org/docs/handbook/2/…
标签: typescript