TypeScript: Basic and Advanced Types
1. Primitive Types
TypeScript allows you to explicitly declare all of JavaScript's basic data types.
let isDone: boolean = false;
let age: number = 30;
let userName: string = "Alice";
let list: number[] = [1, 2, 3]; // Array
let tuple: [string, number] = ["hello", 10]; // Tuple
2. Union and Intersection
- Union (|): Allows a value to be one of several types.
- Intersection (&): Combines multiple types into one.
// Union
let code: string | number = 101;
code = "A101";
// Intersection
interface Person { name: string; }
interface Employee { id: number; }
type Staff = Person & Employee;
const newStaff: Staff = { name: "Bob", id: 123 };
3. Any, Unknown, and Never
- Any: Allows any type. (Best to avoid frequent use)
- Unknown: Allows any type but requires type checking before use, making it safer than
any. - Never: Represents the type of values that reflect something that will never occur (e.g., a function that always throws an error).
4. Enum (Enumerated Type)
Enums allow you to define a set of named constants, either as numbers or strings.
enum Direction {
Up = 1,
Down,
Left,
Right,
}
let move: Direction = Direction.Up;