I am currently working with Typescript and have strict null checking enabled. Whenever I try to compile the code below, I receive an error stating "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;
}
}
It is clear that the key in inverseMap must not allow null values due to the type constraint. When I attempt to change the type of inverseMap to the following:
var inverseMap: { [key: string | null]: number } = {};
I encounter the error "Index signature parameter type must be 'string' or 'number'." This seems strange because in Javascript, using null as an index is permissible. For instance, executing the following code in a browser will result in no errors:
var map = {};
map[null] = 3;
map[null];
The output of this would be 3. Is there a way to achieve similar behavior in Typescript, or does Typescript lack the capability to handle such scenarios?