Typescript
Menu
Union
- Union types in TypeScript allow you to define a variable that can contain multiple types.
- This feature increases flexibility while maintaining type safety.
- Below, key aspects of union types are explained in bullet points along with coding examples
Definition of Union Types
- Syntax: A union type is defined using the pipe (|) symbol to separate multiple types.
let variable: string | number; // This variable can be either a string or a number.
- Syntax: A union type is defined using the pipe (|) symbol to separate multiple types.
Assigning Values to Union Types
- You can assign values of any of the specified types to a union type variable.
let code: string | number;
code = 123; // Valid: number
code = "ABC"; // Valid: string
// code = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
- You can assign values of any of the specified types to a union type variable.
Union Types in Function Parameters
- Union types can be used as parameter types in functions, allowing for more flexible function signatures.
function printId(id: string | number) {
console.log(`ID is: ${id}`);
}
printId("abc"); // Outputs: ID is: abc
printId(123); // Outputs: ID is: 123
- Union types can be used as parameter types in functions, allowing for more flexible function signatures.
Using Union Types with Literal Types
- You can create union types that include specific literal values, enhancing type safety.
type Status = "success" | "failure";
function printStatus(status: Status) {
console.log(`Status is: ${status}`);
}
printStatus("success"); // Valid
// printStatus("error"); // Error: Argument of type '"error"' is not assignable to parameter of type 'Status'.
- You can create union types that include specific literal values, enhancing type safety.
Union Types with Custom Types
- You can define union types using custom types or interfaces.
interface Dog {
bark(): void;
}
interface Cat {
meow(): void;
}
type Pet = Dog | Cat;
function makeSound(pet: Pet) {
if ("bark" in pet) {
pet.bark(); // TypeScript knows pet is a Dog here.
} else {
pet.meow(); // TypeScript knows pet is a Cat here.
}
}
- You can define union types using custom types or interfaces.
Discriminated Unions
- A discriminated union uses a common property (discriminator) to differentiate between types within the union.
type NetworkLoadingState = { state: "loading" };
type NetworkFailedState = { state: "failed"; code: number };
type NetworkSuccessState = { state: "success"; response: object };
type NetworkState = NetworkLoadingState | NetworkFailedState | NetworkSuccessState;
function handleNetworkState(state: NetworkState) {
switch (state.state) {
case "loading":
console.log("Loading...");
break;
case "failed":
console.log(`Failed with code ${state.code}`);
break;
case "success":
console.log("Success!", state.response);
break;
}
}
- A discriminated union uses a common property (discriminator) to differentiate between types within the union.
Limitations of Union Types
- While union types provide flexibility, you must handle each possible type appropriately to avoid runtime errors.
function printLength(value: string | number) {
// console.log(value.length); // Error: Property 'length' does not exist on type 'number'.
if (typeof value === "string") {
console.log(value.length); // Safe to use length property here.
}
}
- While union types provide flexibility, you must handle each possible type appropriately to avoid runtime errors.
Conclusion
- Union types in TypeScript are a powerful feature that allows variables and function parameters to accept multiple types, increasing flexibility while maintaining type safety.
- When you understand how to effectively define and use union types, you can write more robust and maintainable TypeScript code.