TypeScript Course
TypeScript
/
Beginner

Array Types & Tuples

Definition

Defining the type of elements that an array is allowed to hold. Tuples are a special type of array with a fixed length and specific types at specific indexes.

Explain Like I'm New

An Array Type says: 'This box can hold an infinite number of Strings, but absolutely NO numbers'. A Tuple says: 'This box holds exactly two things: the first must be a String, the second must be a Number.'

Real World Example

Typing a list of string IDs: `string[]`. Typing the return value of React's `useState`: `[number, (val: number) => void]`. This is a classic Tuple!

Common Use Cases

  • •Lists of data
  • •React hooks returns (Tuples)
  • •CSV data rows

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • What are the two syntaxes for typing an array?

intermediate

  • What is a Tuple?

advanced

  • Can you push a new element into a Tuple?

Flash Cards

Question

What are the two syntaxes?

Click to reveal answer
Answer

`number[]` and `Array<number>`. They are functionally identical, but `number[]` is generally preferred for readability.

Question

Can you push into a Tuple?

Click to reveal answer
Answer

Yes. Ironically, TS only enforces Tuple lengths on assignment. If you define `let tuple: [string, number] = ['A', 1]`, TS allows you to do `tuple.push('B')`. This is a known quirk in the TS type system.