TypeScript's Basic Types: The Building Blocks
TypeScript builds on JavaScript's primitives (`string`, `number`, `boolean`) by letting you explicitly declare a variable's type. This is the foundation for catching errors early. The main footgun is confusing tuples `[string, number]` with flexible arrays.
WHY IT EXISTS: JavaScript is dynamically typed, meaning a variable's type isn't known until the program runs. This can cause unexpected errors. TypeScript adds a static type system on top of JavaScript to help developers define what kind of data a variable should hold, catching type-related bugs during development.
THE MENTAL MODEL: Think of TypeScript's basic types as explicit labels for your data containers. Instead of letting JavaScript infer a variable's type at runtime, you declare its intent upfront, such as let age: number;. This makes your code more predictable, self-documenting, and easier to reason about.
HOW IT WORKS: TypeScript supports the same primitive types as JavaScript, but allows you to explicitly annotate them. The core types are: boolean: A simple true/false value. let isDone: boolean = false; number: For all floating-point numbers, including decimal, hex, binary, and octal literals. let decimal: number = 6; bigint: For integers larger than the number type can safely handle. let big: bigint = 100n; string: For textual data, using single quotes, double quotes, or backticks for template strings with embedded expressions like ${expr}. let color: string = "blue"; Array: A list of elements of the same type, written as number[] or Array<number>. Tuple: An array with a fixed number of elements whose types are known but can differ. let x: [string, number]; x = ["hello", 10];
WHEN TO USE IT: Basic types are the foundation of any TypeScript application. You use them to declare variables, define function parameters, and specify return values. Use primitives (string, number, boolean) for simple values. Use arrays for variable-length lists of a single type. Use tuples for fixed-length structures where element position and type are both important.
WHEN NOT TO USE IT: Don't use a tuple when you need a variable-length list of items of the same type; an array is the correct tool for that job. For example, use number[] for a list of scores, not a tuple. Using a tuple incorrectly restricts you to a fixed length and type order where you need flexibility.
ONE CANONICAL EXAMPLE: This example shows how string and number types work together using a template literal. let fullName: string = Bob Bobbington; let age: number = 37; let sentence: string = Hello, my name is {fullName}. I'll be {age + 1} years old next month.;
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.