TypeScript Basic Types
TypeScript adds type annotations to describe what kind of value a variable should hold. The most common basic types are `string`, `number`, and `boolean`, matching the primitive types already found in JavaScript.
Once a variable is annotated with a type, TypeScript will produce an error if you try to assign a value of a different type to it, catching mistakes immediately in your editor.
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;string, number, boolean
`string` holds text, `number` holds any numeric value (integer or decimal), and `boolean` holds true or false. These cover most simple values in everyday code.
Type annotations
You add a type annotation with a colon after the variable name, like `let age: number = 25;`. TypeScript then enforces that type for the lifetime of the variable.
let name: string = "Alice";
let age: number = 30;
let isActive: boolean = true;
console.log(name, age, isActive);Alice 30 trueThree variables are declared with explicit basic types.
let score: number = 10;
// score = "high"; // Error: string is not assignable to number
score = 20;
console.log(score);20TypeScript would reject assigning a string to a number-typed variable.
Key points
- string, number, and boolean are the most common basic types.
- Type annotations use a colon after the variable name.
- Assigning the wrong type causes a compile-time error.
- TypeScript's number type covers both integers and decimals.
