Starbucks Admin
Starbucks Admin

Reputation: 937

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?

Upvotes: 0

Views: 100

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

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.

Upvotes: 2

Related Questions