Primitive Types
TypeScript supports all JavaScript primitives with explicit type annotations.
Basic Types:
- string: Text data
- number: All numbers (integers and floats)
- boolean: true or false
- null and undefined: Their own types
- symbol: Unique identifiers
- bigint: Large integers
Type Annotations: Use colon (:) followed by the type name.
Type Inference: TypeScript can often figure out types from context. You don't always need explicit annotations.
any Type: Opts out of type checking. Avoid when possible.
unknown Type: Safer alternative to any. Must check type before using.
never Type: For functions that never return (throw or infinite loop).
void Type: For functions that don't return a value.
Code Examples
Primitive Typestypescript
// Explicit type annotations
let name: string = "Alice";
let age: number = 30;
let isStudent: boolean = false;
// Type inference - explicit annotations optional
let city = "New York"; // TypeScript infers string
let count = 42; // TypeScript infers number
let active = true; // TypeScript infers boolean
// Arrays
let numbers: number[] = [1, 2, 3];
let strings: Array<string> = ["a", "b", "c"];
// Tuple - fixed length, specific types per position
let point: [number, number] = [10, 20];
let person: [string, number] = ["Alice", 30];
// any - avoid if possible
let anything: any = "hello";
anything = 42; // OK, but loses type safety
anything = true; // Still OK, no checking
// unknown - safer than any
let something: unknown = "hello";
// let str: string = something; // Error!
if (typeof something === "string") {
let str: string = something; // OK after type check
}
// void - function returns nothing
function logMessage(msg: string): void {
console.log(msg);
}
// never - function never returns
function throwError(msg: string): never {
throw new Error(msg);
}Use type inference when types are obvious, and explicit annotations for function parameters and complex types.
Quick Quiz
1. What's the difference between 'any' and 'unknown'?
2. What type does TypeScript infer for: let x = 42?
Was this lesson helpful?