Declaring and initializing a Dictionary in TypeScript
Hello colleagues! I'm new to TypeScript (previously wrote in plain JS) and encountered a problem when declaring a dictionary (associative array). In JavaScript I did this:
```typescript
let dict = {};
dict["key1"] = "value1";
dict["key2"] = 123;
```
And it worked fine. But in TypeScript I need to strictly type the dictionary where keys are strings and values are numbers. I tried several options, but everywhere I get compilation errors or strange behavior.
Option 1:
```typescript
let dict = {};
dict["apple"] = 5; // Error: Element implicitly has an 'any' type
```
Option 2:
```typescript
let dict: object = {};
dict["apple"] = 5; // Error: Property 'apple' does not exist on type 'object'
```
Option 3:
```typescript
let dict: { [key: string]: number } = {};
```
No answers yet.
Log in to leave an answer
Blogs