简体   繁体   中英

What does this Typescript syntax mean

export declare type SomeType = {
   [key: string] : string
};

What exactly does this syntax mean? We are exporting a custom type alias called SomeType that is an object that has a property that is called ____ and is of value ____ ?

It means that an object of type SomeType can only have string properties with string values:

Example:

// Valid
{

    firstName: 'John',
    lastName: 'Smith'

},

// Invalid
{

    firstName: 'John',
    age: 10

}

This syntax is called Index Signature .

This is a key/value structure. The key is a string and the value is a string

SomeType = {
   'a-string-key' : 'a-string-value'
};

Basically, Typescript is a static typed version of javascript. In this case, we have a type called SomeType which is an Object. And we are also mentioning the object's key and value type in this manner - [key: string]: string .

In your case, SomeType will only accept a key of string and value of string. Else, It will throw a type error.

Eg: { "name": "user"} is valid and {"name" : 10 } is invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM