无法 'index type' 使用字符串变量
Unable to 'index type' using a string variable
如果值存在,我正在尝试反转对象的字段,但我遇到了一些我无法破译的错误。
interface Control {
name1: boolean;
name2: boolean;
...
}
const values = ['name1', 'name2', ...];
const control: Control = {
name1: false,
name2: false,
...
}
for (const value of values) {
if ((value in control) {
control[value] = !control[value]; // error
}
}
错误信息:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Control'.
No index signature with a parameter of type 'string' was found on type 'Control'.ts(7053)
但是,如果我显式传递对象的字段之一,例如 control['name1']
,错误就会消失。
有什么我不明白的地方吗?
TypeScript 不知道您的 values
数组是特定字符串的数组,只知道它是一个 string[]
。试试这个:
interface Control {
name1: boolean;
name2: boolean;
}
const values = ['name1', 'name2'] as const;
const control: Control = {
name1: false,
name2: false,
}
for (const value of values) {
if (value in control) {
control[value] = !control[value]; // error
}
}
在这种情况下,as const
告诉 TypeScript 将 values
的类型更紧密地指定为 ['name1', 'name2']
,因此当您遍历它时,value
将被输入为 'name1' | 'name2'
并且 TypeScript 将理解这些值可用于索引 Control
.
value
变量在应用程序运行时可以是任何值,TypeScript 不知道它是 control
对象中定义的有效键。因此它不能简单地推断出 control[value]
.
的值类型
但是修复非常简单,所有需要做的就是通过使用 [=16] 告诉 TypeScript values
数组只包含来自 Control
类型的有效键=]语法:
const values: (keyof Control)[] = ['name1', 'name2'];
这里是link到Playground。
如果值存在,我正在尝试反转对象的字段,但我遇到了一些我无法破译的错误。
interface Control {
name1: boolean;
name2: boolean;
...
}
const values = ['name1', 'name2', ...];
const control: Control = {
name1: false,
name2: false,
...
}
for (const value of values) {
if ((value in control) {
control[value] = !control[value]; // error
}
}
错误信息:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Control'.
No index signature with a parameter of type 'string' was found on type 'Control'.ts(7053)
但是,如果我显式传递对象的字段之一,例如 control['name1']
,错误就会消失。
有什么我不明白的地方吗?
TypeScript 不知道您的 values
数组是特定字符串的数组,只知道它是一个 string[]
。试试这个:
interface Control {
name1: boolean;
name2: boolean;
}
const values = ['name1', 'name2'] as const;
const control: Control = {
name1: false,
name2: false,
}
for (const value of values) {
if (value in control) {
control[value] = !control[value]; // error
}
}
在这种情况下,as const
告诉 TypeScript 将 values
的类型更紧密地指定为 ['name1', 'name2']
,因此当您遍历它时,value
将被输入为 'name1' | 'name2'
并且 TypeScript 将理解这些值可用于索引 Control
.
value
变量在应用程序运行时可以是任何值,TypeScript 不知道它是 control
对象中定义的有效键。因此它不能简单地推断出 control[value]
.
但是修复非常简单,所有需要做的就是通过使用 [=16] 告诉 TypeScript values
数组只包含来自 Control
类型的有效键=]语法:
const values: (keyof Control)[] = ['name1', 'name2'];
这里是link到Playground。