TypeScript's has Indexable type which let us describe types we can index into. e.g. One can define an string array like this:
interface StringArray {
[key: number]: string;
}
let x: StringArray = ['Sheldon', 'Cooper'];
x[0] = 'John';
x[1] = 'Snow';
By looking at the index signature [key: number]: string; what I understand is, it defines the name of the key/index: key and the type of the key: string, and the type of the value which is returned i.e. number. Now when I change type of the key to string I get 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';
I am not able to understand why it shows up the warning when I change key's type to string. Why it's not happening when key 's type is numeric. Is it because of array cause array indexes are numeric?
And what happens when we have both indexed type and other properties.
Example 1: It shows error with indexer type
interface NumberDictionary {
[index: string]: number;
length: number; // ok, length is a number
name: string; // error, the type of 'name' is not a subtype of the indexer
}
Example 2: It does not shows error when I change type of [index:string] to [index: number]
interface NumberDictionary {
[index: number]: number;
length: number; // ok, length is a number
name: string; // after chaning `index` type to number it's does'nt show error
}