Union and intersection types

In the previous section, we mentioned union types but haven't covered them as yet. Let's fix that right away – it will only be a small detour and will prove very useful later on!

Union types allow us to define new types by joining existing ones together using the | (pipe) character. When you use a union type, you can only access the members that are common to all those types in the union.

A great example is that you can use a union instead of any to indicate that you accept either one type or the other:

interface BoardGame { 
    name: string; 
    description: string; 
    minimalAge: number; 
    players: string; 
    duration: string; 
} 
 
interface VideoGame { 
    name: string;
    description: string; 
    minimalAge: number; 
    players: string; 
    online: boolean; 
} 
 
function displayGame(game: VideoGame | BoardGame) { 
    console.log(`Game name: ${game.name}`); 
} 

Here, our displayGame function allows either a VideoGame or a BoardGame object to be passed in. This is cleaner than allowing any, don't you think? If we use autocompletion, we can only see the members that are available in both types:

Another closely related concept is intersection types, which allow you to combine types (such as interfaces, classes, and custom types/aliases) so that you have all the properties and members of both types at your disposal.

This is an example of how to mix concepts with TypeScript, without relying on object-oriented principles such as inheritance. Using intersections, you can create new types that combine interfaces, classes, and custom types that are not related to each other at all.

The following is an example:

interface Person { 
    name: string; 
    age: number; 
} 
 
interface Address { 
    street: string;
    streetNumber: number;
    town: string;
    postalCode: number;
    country: string;
} 
 
type PersonWithAddress = Person & Address; 
 
function displayPerson(person: PersonWithAddress) { 
    console.log(`${person.name} lives in ${person.country}`); 
} 
 
let person: PersonWithAddress = { 
    name: "Foo", 
    age: 42, 
    street: "UnknownStreet", 
    streetNumber: 1, 
    postalCode: 1337, 
    town: "UnknownTown", 
    country: "Bar" 
}; 
 
displayPerson(person); // Foo lives in Bar 

Here, the PersonWithAddress type is an intersection of the Person and Address interfaces. The person object that we create must have the properties of both.

If you want to mix unrelated classes together, then you should be using mixins: https://www.typescriptlang.org/docs/handbook/mixins.html. You can actually create an intersection with a class and interface but it doesn't make much sense to do this as it will only take the properties of both types into consideration, which is probably not what you want.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.48.135