Reputation: 115
In TypeScript can declare strongly-typed Array Types
But errors (from compiller) for the next snippet very strange. Could someone explain me error cases?
interface SomeArray1 {
[index: number]: string;
}
var my1: SomeArray1;
my1["ab"] = 12; // <-- why this line is OK?
my1["ab"] = "ab"; // <-- why this line is OK?
my1[12] = "ab";
my1[12] = 12; // <-- error
//-----------------------------
interface SomeArray2 {
[index: string]: number;
}
var my2: SomeArray2;
my2["ab"] = 12;
my2["ab"] = "ab"; // <-- error
my2[12] = "ab"; // <-- error
my2[12] = 12;
//-----------------------------
interface SomeArray3 {
[index: string]: string;
}
var my3: SomeArray3;
my3["ab"] = 12; // <-- error
my3["ab"] = "ab";
my3[12] = "ab";
my3[12] = 12; // <-- error
Open sample in playground
Upvotes: 1
Views: 1978
Reputation: 106620
In my opinion, the documentation is confusing because the array type it describes does not constrain exclusively to an array. For example, the following would be allowed:
var my1: SomeArray1 = {};
What's being talked about, is more like a key-value/dictionary-like type where, in the case of SomeArray1
, the key is a number
and the value is a string
.
It would make more sense if it were instead defined as an array type with a string value constraint:
var my1: Array<string> = [];
Or even a type alias:
type SomeArray1 = Array<string>;
var my1: SomeArray1 = [];
In both these cases, assigning {}
to the variable would not be allowed.
All the errors are very similar. The main reason they are happening is because either there is a string
value constraint and it is being assigned a number
or vice-versa.
It is weird because the type constraint doesn't seem to be working on the index/key. I am certain this used to work. This is either a bug in the compiler or the typescript team decided to change this. I've opened up an issue to check.
And the response:
We changed the behavior here because (at runtime) numbers are implicitly converted to strings during index operations. Basically, a string indexer is a "superset" of a number indexer.
Upvotes: 1