Kodokon kodokon.com

Primitive types, arrays and simple unions

Learn the three basic types, how to type an array, and how to create type unions.

7 min · 3 questions

Open this lesson in Kodokon

Primitive types are the basic building blocks of TypeScript. The three most common are: string for texts (always in quotes), number for all numbers (integers and decimals alike) and boolean for the values true or false. Note that they are written in lowercase.

TYPESCRIPT
let city: string = "Paris";
let temperature: number = 21.5;
let isRaining: boolean = false;
One example of each primitive type.

An array is an ordered list of values. To type it, you write the type of the elements followed by square brackets: number[] reads as "array of numbers". TypeScript then checks every element you add.

TYPESCRIPT
const scores: number[] = [12, 15, 9];
const guests: string[] = ["Nadia", "Louis"];

scores.push(18); // accepted: 18 is a number
// scores.push("twenty"); -> error: not a number
The array always keeps the same element type.

Sometimes a value can legitimately have several types. A union is written with a vertical bar | and reads as "or": the type string | number accepts either a text or a number. You can also create a union of specific values to restrict the possible choices.

TYPESCRIPT
let answer: string | number;
answer = "forty-two"; // accepted
answer = 42;          // also accepted

type Size = "small" | "medium" | "large";
let cupSize: Size = "medium";
// cupSize = "xl"; -> error: value not allowed
Two unions: a union of types, a union of values.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which type would you use for the value true?
    • string
    • number
    • boolean
  2. How do you declare an array that only contains numbers?
    • let list: number[]
    • let list: [number]
    • let list: array
  3. What does the type string | number mean?
    • The value is both a text and a number
    • The value is either a text or a number
    • The value must be a text
    • The value can be anything