Typescript intersection types
Created By: chatGPT
Intersection types in TypeScript allow you to combine multiple types into a single type that has all the properties of the combined types. This is particularly useful when you want to create a new type that has a blend of features from multiple sources.
type A = { a: number; b: string; }
type B = { b: number; c: boolean; }
// Intersection type combining A and B
type C = A & B;
const example: C = {
a: 1,
b: 2,
c: true
};
When you use intersection types, you can ensure that the object you create adheres to the structure of both types. In the example above, C represents an intersection of A and B, meaning it must contain properties from both.
console.log(example.a); // Outputs: 1
console.log(example.b); // Outputs: 2
console.log(example.c); // Outputs: true
If the intersection types have properties with the same name, the resulting type will have that property with the type of the union of the types specified. This means that careful attention is required to avoid confusion in such scenarios.
type D = { a: number }
type E = { a: string }
type F = D & E;
const conflictingExample: F = {
a: 42 // This would throw an error because 'a' needs to be both number and string
};
To manage this, it may be better to avoid naming collisions in your intersection types or handle such cases explicitly by defining unique properties. This enhances code clarity and helps maintain strong typing.
type D = { a: number; }
type E = { b: string; }
type G = D & E;
const resolvedExample: G = {
a: 42,
b: 'Hello'
};
Intersection types are powerful and can be leveraged in function parameters as well. When you want to ensure that a function can accept an argument that satisfies multiple types, intersection types can be the perfect solution.
function displayInfo(item: A & B) {
console.log(item.a);
console.log(item.b);
console.log(item.c);
}
displayInfo(example);