TypeScript: Intersection Type Examples

Below are 2 examples of Intersection Types in TypeScript. The first one uses Interfaces and the second one uses Type Aliases.
Example 1: Intersection Types and Interfaces
The code:
// Kindacode.com
interface BudgetMeal {
mainDish: string;
sideDish: string;
}
interface QuickMeal {
snack: string;
drink: string;
}
interface FullMeal extends BudgetMeal, QuickMeal {}
const meal: FullMeal = {
mainDish: 'Fried turkey',
sideDish: 'Seafoam salad',
snack: 'Mini pancake',
drink: 'Pumpkin juice'
}
console.log(meal);
Output:
{mainDish: "Fried turkey", sideDish: "Seafoam salad", snack: "Mini pancake", drink: "Pumpkin juice"}
Example 2: Intersection Types and Type Aliases
The code:
// Kindacode.com
type SysAdmin = {
name: string;
privileges: string[];
}
type BackendDeveloper = {
name: string;
hometown: string;
skills: string[];
}
type FrontendDeveloper = {
name: string;
age: number;
skills: string[];
}
type BigBoss = SysAdmin & BackendDeveloper & FrontendDeveloper;
const boss: BigBoss = {
name: 'Alice',
privileges: ['playing video games in working hours'],
hometown: 'Wonderland',
skills: ['node.js', 'react', 'nginx'],
age: 200
}
console.log(boss);
// Just an example
// a real boss doesn't need to be like that one
Output:
{name: "Alice", privileges: Array(1), hometown: "Wonderland", skills: Array(3), age: 200}
What’s Next?
If you’d like to learn more about modern TypeScript, take a look at the following posts:
- TypeScript Example: Defaunt Function Parameters
- React + TypeScript: Using Inline Styles Correctly
- React + TypeScript: Handling Select onChange Event
- React & TypeScript: Using useRef hook example
- React + TypeScript: Handling onFocus and onBlur events
You can also check out our TypeScript category page for the latest tutorials and examples.
Subscribe
0 Comments