Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...