Array type script type

Why is TypeScript allowed? I have indicated a numerical index. Why can I use a string as an index? Visual studio does not report an error.

interface StringArray {
    [index: number]: string;

}

var a: StringArray;
a = { "key": "val" };
var b = a["key"];
+4
source share
3 answers

Problem

This is because the compiler still allows implicit types anythat can occur when accessing an object property using an index:

// Example 1
let dictionary: { [index: number]: string };
let myStringTypedVar = dictionary[5];   // implicitly typed as "string"
let myAnyTypedVar = dictionary["prop"]; // implicitly typed as "any"

// Example 2
let myNumberTypedVar = 5;
let myAnyTypedVar = myNumberTypedVar["prop"]; // implicitly typed as "any"

Fix: compile with --noImplictAny

If you compile your example with --noImplictAny, then this will be an error:

tsc --noImplicitAny example.ts

Outputs:

example.ts (8,9): error TS7017: the signature of an object type index is implicitly of type "any".

--noImplicitAny. Visual Studio --noImplictAny, " " "" "typescript :

Disable Allow Implicit Any

"noImplicitAny": "true" compilerOptions tsconfig.json.

+4

. , .

var array = [];
array.push("One"); // array
array[1]= "Two"; // array
array['key'] = "Three";// object
array.key2 = "Four"; // object
var length = array.length; // Is 2 
+2

, . .

TypeScript 1.5 :

The numerical indexes of signatures specified using the index number define type restrictions for all numerically named properties in the containing type. In particular, in a type with a numerical index of a signature of type T, all properties with a numerical name must have types that can be assigned to T

But, I think you have a good moment. It seems that properties should not be accessible by the row index if you specified only the numeric signature of the index.

+1
source

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


All Articles