The null type cannot be used as an index type

I am using Typescript with strict zero-value checking. When I try to compile the following code, I get the error "type" null "cannot be used as the 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 zero as a key, because a type constraint forbids it. However, if I change the inverseMap type to this:

var inverseMap: { [key: string | null]: number } = {};

I get the error "The type of the index signature parameter must be" string "or" number "." This is strange 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 result is 3. Is there a way to do this in Typescript or Typescript is not smart enough to do this?

+4
3

JavaScript, , (okay Symbol s). (. ). , . ,

var map = {};
map[null] = 3;
map[null];

map["null"]. :

console.log(map["null"]===map[null]); // true

, TypeScript string number . , , , - null, .

- :

function buildInverseMap(source: Array<string | null>) : {[key: string] : number} {
    var inverseMap: { [key: string]: number } = {};
    for (let i = 0; i < source.length; i++) {
        inverseMap[String(source[i])] = i; // coerce to string yourself
    }
    return inverseMap;
}

, source[i] string , TypeScript . String() , , :

const inverseMap = buildInverseMap(['a', 'b', null, 'c']);
const aIndex = inverseMap['a'];
const nullIndex = inverseMap[String(null)];

, ! .

+4

map[null] = 3; , map['null'] = 3; 'null' typescript, .

+2

Javascript null undefined , , , :

let a = {};
a[null] = "i am null";
a[undefined] = "i am undefined";
console.log(a[null] === a["null"]); // true;
console.log(a[undefined] === a["undefined"]); // true;

typescript , string number ( ), .

:

inverseMap[source[i] || "null"] = i;
+2
source

Source: https://habr.com/ru/post/1685039/


All Articles