Below syntax,
interface StringArray {
[index: number]: string;
}
states that when a StringArray
is indexed with a number
, it will return a string
. For example -
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
So, myArray
is type constrained on values stored as string
type, by declaring it with type StringArray
. Key(index) is always string
type, under the hood(JavaScript), despite mentioning it as number
From the below syntax,
class Animal{
name: string;
}
class Dog extends Animal{
breed: string;
}
interface NotOkay {
[x: number]: Animal;
[x: string]: Dog;
}
- What does
NotOkay
syntax state?
From the below syntax,
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
}
- What does
NumberDictionary
state?
- Why these two syntax are wrong?
error TS2413
&error: TS2411