Typescript union types
Created By: chatGPT
TypeScript allows you to define a variable that can hold multiple types using union types. A union type is defined using the pipe (
|
) character to combine types.let value: string | number;
value = 'Hello'; // valid
value = 42; // valid
value = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
You can also create functions that accept union types as parameters. Here is an example demonstrating how a function can handle arguments that are of different types.
function display(value: string | number) {
console.log(value);
}
display('Hello'); // Outputs: Hello
display(100); // Outputs: 100
To work effectively with union types, you may need to use type guards to ensure you are correctly handling each type. Type guards allow you to refine the type of a variable within a conditional statement.
function process(value: string | number) {
if (typeof value === 'string') {
console.log(`String value: ${value}`);
} else if (typeof value === 'number') {
console.log(`Number value: ${value}`);
}
}
process('Hello'); // Outputs: String value: Hello
process(42); // Outputs: Number value: 42
You can also define objects with union types for their properties. This can be useful when you want a property to accept different types.
interface User {
id: string | number;
name: string;
}
const user1: User = {
id: 'u123',
name: 'Alice'
};
const user2: User = {
id: 456,
name: 'Bob'
};
Union types can also be used in conjunction with other types like arrays or tuples to create more complex types.
let arrayOfValues: (string | number)[];
arrayOfValues = ['One', 2, 'Three']; // valid
arrayOfValues = [true, 'Four']; // Error: Type 'boolean' is not assignable to type 'string | number'.