How to specify a type for all values of an object in TypeScript, except for keys?
Hi everyone! I have an object that I use as a dictionary. The keys are strings and the values are numbers. Like this:
```typescript
const myDict = {
apple: 5,
banana: 3,
cherry: 8
};
```
The problem is that TypeScript doesn't check that all values in this object are numbers. If I accidentally write `apple: "five"`, there will be no error because TypeScript infers the type as `{ apple: string | number; banana: number; cherry: number }` instead of `{ [key: string]: number }`.
I tried using `Record`:
```typescript
const myDict: Record = {
apple: 5,
banana: 3,
cherry: 8
};
```
This works, but now I can't get autocompletion for the keys. When I write `myDict.apple`, TypeScript shows that the type is `number`, but it doesn't
No answers yet.
Log in to leave an answer