Search⌘ K

Members of the Same Type

Explore how TypeScript requires all members in an interface with a string index signature to share the same type. Understand why unions of types are limited and how implementing interfaces in classes is affected. Learn how intersections can be used as a workaround for type restrictions.

Same type

The interface defined by members and an index type that uses a string as the key must have all its members to be of type string.

πŸ“œNote: the code below throws an error ❌

TypeScript 3.3.4
interface MyStringDictionaryWithMembers {
[key: string]: string;
m1: string;
m2: number; // Won't transpile, must be a string
}

If we correct the previous example to have m2 to be a string on line 4, the code compiles.

TypeScript 3.3.4
interface MyStringDictionaryWithMembers {
[key: string]: string;
m1: string;
m2: string; // Fixed!
}
...