Understanding Intersection Types in Typescript
- When you see the symbol & in Typescript within the context of types, it signifies an intersection type.
- This combines all the properties from two object types and generates a completely new type.
Here's an Example to Clarify:
type dog = {age: number, woof: Function};
type cat = {age: number, meow: Function};
// The 'weird' type is an intersection of 'cat' and 'dog'
// It must encompass all attributes from both 'cat' and 'dog'
type weird = dog & cat;
const weirdAnimal: weird = {age: 2, woof: () => {'woof'}, meow: () => {'meow'}}
interface extaprop {
color: string
}
type catDog = weird & extaprop; // This combined type now incorporates the additional property 'color'
const weirdAnimal2: catDog = {age: 2, woof: () => {'woof'}, meow: () => {'meow'}, color: 'red'}
// Note that this differs from a union type
// The type below specifies either a cat OR a dog
type dogOrCat = dog | cat;