Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

typescript - How to specify type for a variable?

I am having a variable. It's an array of string arrays. How can I declare it with type.

let map = [ ['key1', 'value1'],['key2', 'value2']  ] ;

I mean for example if I have variable that holds a string I can declare it like this. In the following code I am making it clear that I am declaring a variable whose type is string.

let test:string = 'hello';

So similarly how I can I specify the type for the "map" variable in TypeScript?

question from:https://stackoverflow.com/questions/66066320/how-to-specify-type-for-a-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just for what it's worth, you don't have to declare the type of map. TypeScript will infer the type from the initializer.

But if you wanted to, it would either be

1. An array of arrays of strings: string[][] / Array<Array<string>>

let map: string[][] = [ ['key1', 'value1'],['key2', 'value2']  ] ;

(This is the type TypeScript will infer if you don't specify one.)

Playground link

or

2. An array of string,string tuples: [string, string][] / Array<[string, string]>

let map: [string,string][] = [ ['key1', 'value1'],['key2', 'value2']  ] ;

Playground link

Tuple types...

...allow you to express an array with a fixed number of elements whose types are known, but need not be the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...