Type
In TypeScript, a type defines the shape and constraints of data, specifying what kind of values a variable can hold and what operations can be performed on it.
Overview
Types are the foundation of TypeScript. They allow you to specify what kind of data a variable, function parameter, or return value should be. TypeScript's type system helps catch errors at compile time, provides better IDE support, and makes code more self-documenting and maintainable.
Example
typescript// Primitive types let name: string = 'Alice'; let age: number = 30; let isActive: boolean = true; // Array types let numbers: number[] = [1, 2, 3]; let names: Array<string> = ['Alice', 'Bob']; // Object types let user: { name: string; age: number } = { name: 'Alice', age: 30 }; // Function types function greet(name: string): string { return `Hello, ${name}!`; } // Union types let id: string | number = 123; id = 'abc'; // Also valid // Type aliases type User = { id: number; name: string; email?: string; // Optional property }; const user: User = { id: 1, name: 'Alice' }; // Generic types function identity<T>(arg: T): T { return arg; } const num = identity<number>(42); const str = identity<string>('hello'); // Tuple types let coordinate: [number, number] = [10, 20]; // Literal types let direction: 'north' | 'south' | 'east' | 'west' = 'north';
Key Points
- Defines data shape and constraints
- Catches errors at compile time
- Improves IDE autocomplete and refactoring
- Can be primitive, object, function, or custom
- Supports generics and advanced features
Learn More
- TypeScript - TypeScript language
- Interface - Interface types
- TypeScript Docs: Types