1. Union Types:
Union types allow you to declare a variable with more than one type. It means a variable can hold values of different types.
Example:
// Declaring a variable with a union type let myVar: number | string; // Assigning values myVar = 10; // Valid myVar = "hello"; // Valid myVar = true; // Error: Type 'boolean' is not assignable to type 'number | string'
2. Intersection Types:
Intersection types allow you to combine multiple types into one. It means a variable of an intersection type will have all the properties of each of its constituent types.
Example:
interface Car { make: string; model: string; } interface Electric { battery: string; } type ElectricCar = Car & Electric; // Variable of type ElectricCar will have properties from Car and Electric let myCar: ElectricCar = { make: "Tesla", model: "Model S", battery: "Lithium-ion" };
3. Type Aliases:
Type aliases allow you to create custom names for existing types, making your code more readable and expressive.
Example:
type ID = number; type Name = string; // Using type aliases let userId: ID = 1001; let userName: Name = "John Doe";
4. Conditional Types:
Conditional types allow you to create types that depend on other types. They enable you to define a type based on a condition.
Example:
type CheckType<T> = T extends string ? string : number; let result1: CheckType<string> = "Hello"; // Type of result1 is string let result2: CheckType<number> = 10; // Type of result2 is number
5. Mapped Types:
Mapped types allow you to create new types by transforming each property in an existing type in a specific way.
Example:
interface Person { name: string; age: number; } // Transforming all properties of Person to be read-only type ReadOnlyPerson = { readonly [P in keyof Person]: Person[P]; }; let person: ReadOnlyPerson = { name: "John", age: 30 }; person.name = "Jane"; // Error: Cannot assign to 'name' because it is a read-only property
These advanced types provide powerful tools for creating flexible and expressive TypeScript code. Understanding how to use them effectively can greatly enhance your ability to model complex data structures and enforce type safety in your applications.
0 Comments