TS2538

error TS2538: Type ‘Person’ cannot be used as an index type.

Broken Code ❌

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

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

Fixed Code ✔️

You cannot use an interface as an index type, but you can use all keys of the interface using the keyof type operator:

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

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