What does declaring this type in Typescript mean?

I am new to Typescript and I am reading the code to someone else and I am having problems with this ad:

    private somevar: { [s: string]: string };

What type is this? The square brackets indicate the array, but I'm confused exactly what form it will be in.

+4
source share
2 answers

This is an indexable type. Looking at this expression like variable definition:

let myIndexVar: { [key: string]: number; };
  • : { ... } means an object.
  • [key: string]: number; is the index signature of the object.

Inside the index signature:

  • [key: string]defines the key name keyand key type << 25>.
  • : number; - value type <<27>.

These types are used as follows:

let myIndexVar: { [key: string]: number; } = {};

myIndexVar["key"] = 4; // key is string, value is number

, , . , , , :

Intellisense Example

+10

Typscript docs

. , , , "", [10], ageMap [ "daniel" ]. , , . :

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

, StringArray, . , StringArray number, .

: . , . , , JavaScript . , 100 () "100" (), .

class Animal {
    name: string;
}
class Dog extends Animal {
    breed: string;
}

// Error: indexing with a 'string' will sometimes get you a Dog!
interface NotOkay {
    [x: number]: Animal;
    [x: string]: Dog;
}

"", . , , obj.property obj [ "property" ]. , , -checker :

interface NumberDictionary {
    [index: string]: number;
    length: number;    // ok, length is a number
    name: string;      // error, the type of 'name' is not a subtype of the indexer
}
0

All Articles