I have this code:
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 '{}'.
}
I know the error exists because I have enabled the noImplicitAny
for cleaner code but how is the clean way to set this property?
You can declare a Record
type :
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
}