Deklaration und Initialisierung eines Dictionary in TypeScript
Hallo Kollegen! Ich bin neu in TypeScript (habe vorher in reinem JS geschrieben) und bin auf ein Problem bei der Deklaration eines Dictionary (auch assoziatives Array genannt) gestoßen. In JavaScript habe ich das so gemacht:
```typescript
let dict = {};
dict["key1"] = "value1";
dict["key2"] = 123;
```
Und es hat funktioniert. Aber in TypeScript muss ich das Dictionary streng typisieren, wobei die Keys Strings und die Values Zahlen sind. Ich habe mehrere Varianten ausprobiert, aber überall bekomme ich Compiler-Fehler oder seltsames Verhalten.
Variante 1:
```typescript
let dict = {};
dict["apple"] = 5; // Error: Element implicitly has an 'any' type
```
Variante 2:
```typescript
let dict: object = {};
dict["apple"] = 5; // Error: Property 'apple' does not exist on type 'object'
```
Variante 3:
```typescript
let dict: { [key: string]: number } = {};
```