TypeScript offers an interesting feature called Indexable type, allowing us to define types that we can index into. For example, you can create a string array like this:
interface StringArray {
[key: number]: string;
}
let x: StringArray = ['Sheldon', 'Cooper'];
x[0] = 'John';
x[1] = 'Snow';
Looking at the index signature [key: number]: string;
, it specifies the name of the key/index as key
, the type of the key as string
, and the returned value's type as number
. Consequently, changing the key type to string results in an error.
interface MyStringArray {
[key: string]: string;
}
//Type 'string[]' is not assignable to type 'MyStringArray'.
//Index signature is missing in type 'string[]'.
var y: MyStringArray = ['Sheldon', 'Cooper']; //<- causes the error
y[0] = 'John';
y[1] = 'Snow';
The warning arises when altering the key's type to string
, which raises the question - why does the error occur for a string key but not for a numeric key? Perhaps because arrays use numeric indexes by default?
Furthermore, what happens when combining indexed types with other properties?
Example 1: Error occurs with indexer type:
interface NumberDictionary {
[index: string]: number;
length: number; // ok, length is a number
name: string; // error, 'name' type isn't a subtype of the indexer
}
Example 2: No error is shown when changing [index:string]
to [index: number]
:
interface NumberDictionary {
[index: number]: number;
length: number; // ok, length is a number
name: string; // after changing `index` type to number, no error is displayed
}