Union and Intersection of types in TypeScript

Do you know, TypeScript allows union and Intersection of types? Why you need that? Let us assume you need to create a function that checks whether the passed value is boolean true and returns true, otherwise returns null.

That function may look like below,


function trueOrNull(foo: any): any {
    if (foo === true) {
        return true;
    }
    return undefined;
}
 
console.log(trueOrNull(88)); // null 

As you see, the return type is set to any.  So, even if you return any other type than boolean or null, TypeScript won’t complain about that.


function trueOrNull(foo: any): any {
    if (foo === true) {
        return true;
    }
    return "foo";
}
 
console.log(trueOrNull(88)); // foo 
console.log(trueOrNull(true)); // true 

We can fix it by creating a new type, which is the union of boolean and null.


type nullorbol = boolean | null;

And then change the return type of function from any to nullorbol


function trueOrNull(foo: any): nullorbol {
    if (foo === true) {
        return true;
    }
    return "foo";
}

You will find TypeScript complains about the string return value, and these scenarios union of types is very useful.

Besides union, TypeScript also supports the Intersection of types. The Intersection is represented by &

Let us assume there are two types,


type Student = {
    name: string,
    grade: number
}
 
type Singer = {
    name: string,
    genre: string
}

Say, there is a student who is a singer too. How will you define that student? TypeScript provides Intersection of type for that,


type StudentandSinger = Student & Singer;
 
let foo: StudentandSinger = {
    name: 'foo',
    grade: 6,
    genre: 'Pop'
}
 
console.log(foo);

Since Intersection implies ‘and’ of types, you must provide value for all the fields. Otherwise, TypeScript complains about that. So, the below code snippet will throw an error,


let foo: StudentandSinger = {
    name: 'foo',
    genre: 'Pop'
}

You should get an error as shown below,

And as you have already seen, union means either or both.  So, let us assume there is someone who a student or singer or both.


type StudentorSinger = Student | Singer;
 
let foo: StudentorSinger = {
    name: 'foo',
    genre: 'Pop',
}

In this way, you can work with the union and Intersection of types in TypeScript. I hope you find this post useful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s