Primitive types and arrays
Learn the simple value types in TypeScript and the array types that hold many of them.
- Annotate text, numbers and true or false with string, number and boolean.
- Write string[] or the Array form for a list of strings.
- Use a tuple when an array has a fixed length and order.
- Use a readonly array when a list must not change after it is created.
In plain English
A primitive type describes one simple value. The type string is text, number is any numeric value, and boolean is either true or false. The types null and undefined describe values that are intentionally empty or missing. An array type such as string[] means every item in the list is a string, and the longer Array form means exactly the same thing. A tuple fixes both the length and the order of a small array, and a readonly array promises the list will never be changed.
Step by step
- 1Decide what a single value is: text, a number, or true or false.
- 2Annotate it with string, number or boolean after the variable name.
- 3For a list of values, add square brackets to the element type.
- 4Use a tuple when the list has a fixed number of slots in a fixed order.
- 5Mark an array readonly when nothing is allowed to change it.
let name: string = 'Ada'
let score: number = 42
let passed: boolean = true
let empty: null = null
let missing: undefined = undefined
const names: string[] = ['Ada', 'Grace']
const sameNames: Array<string> = ['Alan', 'Katherine']
const pair: [string, number] = ['Ada', 42]
const fixed: readonly string[] = ['Ada', 'Grace']Common mistakes
- Writing number when the value is text causes a compiler error because a string is not a number.
- Treating null and undefined as the same thing is wrong; null is an intentional empty value and undefined means a value was never set.
- Using string[] to describe an array that holds numbers will fail, because every item in a string[] must be a string.
- Expecting a tuple to work like a normal array is a mistake; a tuple has a fixed length and order.
Type a shopping list
Annotate a tuple that holds an item name and its quantity, then declare a readonly array of strings for the aisle names.
const item = ['apples', 6]
const aisles = ['produce', 'bakery']What does the tuple type [string, number] describe?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.