如何修复 属性 的隐式数组访问
How to FIX implicit any of array access of property
我有这个代码:
function getKey(): string {
return 'foo';
}
function dummy(): void {
const object = {};
const key: string = getKey();
const value: any = 42;
object[key] = value; // ERROR: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
}
我知道错误存在是因为我启用了 noImplicitAny
以获得更清晰的代码,但是设置此 属性 的简洁方法是怎样的?
您可以声明一个 Record
类型:
function getKey(): string {
return 'foo';
}
function dummy(): void {
const object: Record<string, any> = {}; // Here you can define the type of value, example string or number.
const key: string = getKey();
const value: any = 42;
object[key] = value; // Not error
}
我有这个代码:
function getKey(): string {
return 'foo';
}
function dummy(): void {
const object = {};
const key: string = getKey();
const value: any = 42;
object[key] = value; // ERROR: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
}
我知道错误存在是因为我启用了 noImplicitAny
以获得更清晰的代码,但是设置此 属性 的简洁方法是怎样的?
您可以声明一个 Record
类型:
function getKey(): string {
return 'foo';
}
function dummy(): void {
const object: Record<string, any> = {}; // Here you can define the type of value, example string or number.
const key: string = getKey();
const value: any = 42;
object[key] = value; // Not error
}