Union Types and Type Aliases in TypeScript

InstructorAri Picker

Share this video with your friends

Send Tweet

Sometimes we want our function arguments to be able to accept more than 1 type; e.g. a string or an array. This lesson will show us how to assign more than 1 type to a variable with Typescript union types and type aliases.

Vincenzo
~ 6 years ago

Just reporting a typo: let thing = string | number | string[] | boolean; in the transcript should be type thing = string | number | string[] | boolean; as in the video :)

Kristiyan
~ 6 years ago

feel free to use Array.prototype.join instead of forEach ;)

Cristian Gabbanini
~ 6 years ago

Hi, I think it is now possible to perform some checking with union types and not having typescript yell at us. For example:

type foo = { id: number, name: string };
type bar = { count: number, age: number };

type foobar = foo | bar;

function getFooBar(foobar: foobar) {
    if ("id" in foobar) {
        // Here's my foo
        // foobar.count or foobar.age do not exist
        return foobar;
    } 
    if ("count" in foobar) {
        // Here's my bar
        // foobar.id or foobar.name do not exist
        return foobar;
    }
}

If you paste the previous snippet into the typescript playground source panel and highlight every one of the return statements, you will see that typescript is taking into account that the first object is a foo and that the second is a bar.

sumitj18s
~ 4 years ago

I think example in demo.js has. a small mistake in Transcript, i.e., let thing = string | number | string[] | boolean; let returnSomething = (someThing: thing) => { if (typeof someThing === "string" || typeof someThing === "number" || typeof someThing === "boolean") { console.log("somthing = ", someThing); } }

shall be changed to

type thing = string | number | string[] | boolean; let returnSomething = (someThing: thing) => { if (typeof someThing === "string" || typeof someThing === "number" || typeof someThing === "boolean") { console.log("somthing = ", someThing); } }

Lucas Minter
~ 4 years ago

@sumitj18s Thanks for that! I went ahead and got that fixed in the transcripts. (also noticed the typo 'somthing' and fixed that as well)

~ 2 years ago

Sorry, but that voice is really amazing :)