Basic types: primitives, arrays, tuples and unknown

Intermediate

Introduction

Every JavaScript value has a run-time kind: a number, a string, a boolean, an object. TypeScript gives each of these a type so the checker can follow values through the program. This lesson covers the types you will write most often: the primitives, arrays, tuples, the special values null and undefined, and two types for values you know nothing about, any and unknown.

How it works

The primitive types have the same names as typeof gives: number (all numbers, whole or not), string, boolean, bigint for whole numbers of any size (written 10n), and symbol. A literal type is a single value: the type "yes" allows only the string "yes". A const declared with a string is given its literal type, because it can never change; a let gets the wider type string.

An array type is written number[] or, equally, Array<number>. Every item must have that type, and methods know it: scores.push("ten") is an error. A tuple is an array of fixed length with a type for each position, such as [string, number] for a name and a score; reading pair[0] gives a string and pair[1] a number.

In strict mode, null and undefined are not part of other types. A variable that may be empty must say so with a union, written with a vertical bar: let maybe: string | null. TypeScript then refuses maybe.length until you have checked that maybe is not null. This one rule removes the most common crash in JavaScript, reading a property of undefined.

Some values have no type the checker can know, such as the result of JSON.parse. Two types exist for them. any turns checking off: anything goes, and mistakes slip through. unknown accepts any value but lets you use it only after a check, such as typeof data === "object". Use unknown; reach for any only while moving old JavaScript to TypeScript.

The type void means a function returns nothing useful, and never means a function never returns at all, for example because it always throws. You will meet both again with functions.

Example

// Arrays, tuples, null and literal types.
const scores: number[] = [72, 88, 91];
const names: Array<string> = ["Rina", "Arif", "Zoya"];
const pair: [string, number] = ["Rina", 72]; // a tuple: fixed length, a type for each place
let maybe: string | null = null;
let notYet: number | undefined;

scores.push(65);
maybe = names[0].toUpperCase();
notYet = scores.length;
console.log(scores, pair, maybe, notYet);

const data: unknown = JSON.parse('{"ok": true}');
if (typeof data === "object" && data !== null) {
  console.log("an object:", data);
}

const fixed = "yes"; // a const string has the literal type "yes"
let changing = "no"; // a let string has the type string
changing = fixed;
console.log(changing);
Open in compiler

Line by line

  1. scores is a number[] and names an Array<string>: the two spellings mean the same.
  2. pair is a tuple: position 0 is a string, position 1 a number.
  3. maybe may hold a string or null; notYet may hold a number or undefined, and starts undefined.
  4. data comes from JSON.parse, so it is unknown; it is printed only after checking it is a non-null object.
  5. fixed has the literal type "yes"; assigning it to the string variable changing is allowed.

Expected result

[ 72, 88, 91, 65 ] [ 'Rina', 72 ] RINA 4
an object: { ok: true }
yes

In the real world

APIs return JSON, and well-written TypeScript code treats each response as unknown until it has been checked, often with a validation library that turns the check into a type. Strict null checking is the reason TypeScript code rarely fails with "cannot read properties of undefined": the compiler has already asked, at every such line, what happens when the value is missing.

Common mistakes

  • Using any to make an error go away: the mistake is still there, now hidden.
  • Writing String or Number with capitals as types; those are wrapper objects, and the types are lowercase.
  • Forgetting that array indexing can go past the end: names[10] is typed as a string but is undefined at run time.
  • Mixing up tuples and arrays: [string, number] is two items exactly, (string | number)[] is any number of either.

Best practices

  • Let inference type most variables, and annotate when a variable starts empty, such as const list: string[] = [].
  • Use unknown for data from outside the program, and check it before use.
  • Write T | null or T | undefined whenever a value may be missing, and handle that case.

Summary

TypeScript's basic types are the primitives (number, string, boolean, bigint), arrays (T[]), tuples with a type per position, literal types, and null and undefined, which strict mode keeps separate so missing values must be handled. For values of unknown shape, unknown keeps you safe and any does not.

Quick check

1. Which type describes exactly two items, a string then a number?
2. In strict mode, can a variable of type string hold null?
3. What is the type of greeting in const greeting = 'hi'?
4. Why prefer unknown to any for JSON.parse's result?

Key takeaways

  • Arrays are T[]; tuples fix the length and the type at each position.
  • In strict mode, null and undefined must be allowed explicitly, with a union such as string | null.
  • Prefer unknown to any: unknown forces a check, any skips it.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.