TS7053

error TS7053: Element implicitly has an ‘any‘ type because expression of type ‘string‘ can’t be used to index type ‘Person‘. No index signature with a parameter of type ‘string‘ was found on type ‘Person‘.

Broken Code ❌

1
2
3
4
5
6
7
interface Person {
name: string;
}

function getValue(person: Person, key: string): string {
return person[key];
}

Fixed Code ✔️

There are multiple ways to solve the error. You can define an index signature for the Person interface which will allow all strings:

1
2
3
4
5
6
7
8
interface Person {
[index: string]: string;
name: string;
}

function getValue(person: Person, key: string): string {
return person[key];
}

However, this is not recommend as it will allow you to access keys that are not defined (like age):

1
2
3
4
5
6
7
8
9
10
interface Person {
[index: string]: string;
name: string;
}

function getValue(person: Person, key: string): string {
return person[key];
}

console.log(getValue({name: 'Benny'}, 'age')); // returns `undefined`

The better solution is using the keyof type operator which creates a literal union of its keys:

1
2
3
4
5
6
7
interface Person {
name: string;
}

function getValue(person: Person, key: keyof Person): string {
return person[key];
}