【发布时间】:2020-05-19 08:00:42
【问题描述】:
假设我有一个非常简化的示例来说明我的代码中发生的事情:
interface I {
n?: number;
s?: string;
}
const a: I = {
n: 1,
}
const b: I = {
n: 2,
s: 'b',
}
const props = ['n', 's'] as const;
for (const prop of props) {
if (!a[prop]) {
// here, I get the following error:
// TS2322: Type 'string | number' is not assignable to type 'never'.
// Type 'string' is not assignable to type 'never'.
a[prop] = b[prop];
}
}
作为a 和b 相同的类型,访问相同的属性prop... 不应该是可能的吗?
- 如果
b[prop]是一个数字,那么a[prop]应该接受数字 - 如果
b[prop]是一个字符串,那么a[prop]应该接受字符串 - 如果
b[prop]未定义,是因为该属性是可选的?
那么,我在这里错过了什么?
更新:由于我过于简化了我的示例,答案是删除了as const 部分......但我认为这是由于我的环境,因为我使用的是strict: true在tsconfig.json...
然后,如果我尝试在不使用 as const 的情况下访问,我会收到 TS7053 错误:
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“I”。
在“I”类型上找不到带有“字符串”类型参数的索引签名。
修复添加as const 或执行for(const prop of props as ('n' | 's')[]) {
然后是我收到原始错误的时候(可以使用as any 轻松修复,但我正在努力避免这种情况)
【问题讨论】:
标签: typescript