- A type in Typescript is a way to define the structure & behavior of data, allowing us to specify what kinds of values a variable can hold.
- Types can represent primitive types, complex structures, or combinations of both, providing flexibility in type-checking.
Key points:
- Primitive Types: Includes
string, number, boolean, null, undefined, and void.
- Complex Types: Can include arrays, tuples, objects, and function types.
- Type Aliases: You can create custom types using type aliases for clarity and reusability.
- Union and Intersection Types: Allows the combination of multiple types using unions (
|) and intersections (&).
Example
type Point = {
x: number;
y: number;
}
let point:Point = {x: 10, y: 20};
type ID = string | number; // Union type
let userId: ID = "user123" // Valid
userId = 123; // Also valid