Primitive Types Unions and Type Aliases
Annotate variables with string, number, boolean, and arrays. Create union types with | and give them readable names with type aliases.
Annotating Variables
Add type annotations with a colon after the variable name. TypeScript infers types when possible — add explicit annotations where inference is unclear or for documentation.
let score: number = 0;
const greeting: string = 'Hello';
let active: boolean = true;
let data: null = null;
let placeholder: undefined;
// Inferred (no annotation needed):
const pi = 3.14; // TypeScript knows this is numberPrimitive Types
TypeScript's primitive types map to JavaScript's primitives: string, number (no integer/float distinction), boolean, null, undefined, symbol, bigint.
function greet(name: string): string {
return `Hello, ${name}`;
}
function double(n: number): number {
return n * 2;
}
function toggle(active: boolean): boolean {
return !active;
}All lessons in this course
- Why TypeScript: Types Catch Bugs at Compile Time
- Primitive Types Unions and Type Aliases
- Interfaces and Object Types
- Compiling TS and tsconfig.json