How to declare a fixed-length array in TypeScript?
Hi! I recently started learning TypeScript and ran into a problem. I need to declare an array that will always contain a strictly defined number of elements — for example, exactly 3 numbers. I tried writing it like this:
```typescript
let arr: number[3] = [1, 2, 3];
```
But TypeScript complains: `'number[3]' refers to a value, but is being used as a type here`. Then I tried:
```typescript
let arr: [number, number, number] = [1, 2, 3];
```
This worked! But I want to understand if there is a more general way to create a fixed-length array, for example, for 100 elements? Writing `[number, number, number, ... 100 times]` manually is terrible.
Also, I noticed that if I write:
```typescript
let arr: [number, number, number] = [1, 2, 3];
arr.push(4); // doesn't complain
```
Typ
No answers yet.
Log in to leave an answer