Learn the three basic types, how to type an array, and how to create type unions.
Open this lesson in KodokonPrimitive 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.
let city: string = "Paris";
let temperature: number = 21.5;
let isRaining: boolean = false;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.
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 numberSometimes 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.
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