I'm using Typescript with strict null checking enabled. When I try to compile the following code I get the error "type 'null' cannot be used as an index type."
function buildInverseMap(source: Array<string | null>) {
var inverseMap: { [key: string]: number } = {};
for (let i = 0; i < source.length; i++) {
inverseMap[source[i]] = i;
}
}
Obviously inverseMap cannot have null as a key because the type constraint disallows it. However if I change the type of inverseMap to this:
var inverseMap: { [key: string | null]: number } = {};
I get the error "Index signature parameter type must be 'string' or 'number'." This is odd because in Javascript it is legal to use null as an index. For example, if you run the following code in your browser:
var map = {};
map[null] = 3;
map[null];
The output is 3. Is there a way to make this happen in Typescript or is Typescript not smart enough to do this?