Defining an array with multiple types in TypeScript: union types vs tuples
Hi everyone! I recently started learning TypeScript and ran into a problem when declaring an array that can contain elements of different types.
I have a function that takes an array of strings and numbers. For example, I want to store a user's ID (number) and name (string) in one array. Here's how I tried to do it:
```typescript
let users = [1, "Alice", 2, "Bob"];
```
TypeScript automatically infers the type `(string | number)[]`, which seems to work. But then I needed to strictly control the order: first a number, then a string. I tried this:
```typescript
let user: [number, string] = [1, "Alice"];
```
That works fine. But what if I want an array of such tuples? I wrote:
```typescript
let users: [number, string][] = [[1, "Alice"], [2, "Bob"]];
```
No answers yet.
Log in to leave an answer
Blogs