typescript中迭代的索引签名
我们都可以看到这段代码是有效的javascript:typescript中迭代的索引签名,typescript,index-signature,Typescript,Index Signature,我们都可以看到这段代码是有效的javascript: const myObj = { foo: "string", bar: 123, baz: "important stuff" }; ['foo', 'bar'].forEach((key) => { delete myObj[key]; }); 元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型“{foo:string;bar:number;baz:string;}”。 在类型{foo:
const myObj = {
foo: "string",
bar: 123,
baz: "important stuff"
};
['foo', 'bar'].forEach((key) => {
delete myObj[key];
});
元素隐式具有“any”类型,因为类型为“string”的表达式不能用于索引类型“{foo:string;bar:number;baz:string;}”。
在类型{foo:string;bar:number;baz:string;}上未找到具有“string”类型参数的索引签名
那么,实现这种类型脚本兼容的最佳方法是什么呢?一种解决方法是:
(['foo', 'bar'] as (keyof typeof myObj)[]).forEach((key) => {
delete myObj[key];
});
但这并不能防止在数组字符串中键入错误。尝试键入数组:
const myObj = {
foo: "string",
bar: 123,
baz: "important stuff"
};
const myArray: (keyof typeof myObj)[] = ['foo', 'bar']
myArray.forEach(...)