Basics

Advanced
Types


Table of Contents

In this lesson we will look at some of the advanced types in TypeScript.

Topics on this page:


Union Types

In scenarios where a type can be one of multiple types, a union type is used by separating the different type options with a |.

let myVar : boolean | number = 20;

function displayType( code: string | number )
{
    if( typeof( code ) === 'number' )
        console.log( 'Code is number.' )
    else if( typeof( code ) === 'string' )
        console.log( 'Code is string.' )
}

Intersection Type

An intersection type uses the & symbol to combine multiple types together. This is different than the union type, as a union type says "the resulting type is one of the listed types" whereas the intersection type says "the resulting type is the combination of all listed types".

type Student = {
    id: string;
    age: number;
};

type Employee = {
    companyId: string;
};

let person: Student & Employee;

person.age = 21; // ✅
person.companyId = 'SP302334'; // ✅
person.id = '10033402'; // ✅
person.name = 'Henry'; // ❌ - name does not exist in Student & Employee

Type Assertion

We can tell TypeScript how to interpret some types. We do it by compile-time type casting. For example:

let str : any = 'this is a string';
let len1 = str.length; // not clean code since str is not a separating

// casting one way
let len2 = (<string>> str).length;

// casting another way
let len3 = str as string).length;
console.log( len ); 

Type Alias

To make things confusing, TypeScript also allows you to specify multiple type annotations using a type alias. Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you’d otherwise have to write by hand.

// you can use myString instead of string. it is similar to typedef in C
type myString = string;
let str : myString;


// Animal is an alias to custom type. can be used locally in this file
// better way is to define an interface or a class
type Animal = {
    kind: string;
    weight: number;
};

let dog: Animal;

dog = {
    kind: 'mammal',
    weight: 10,
}; // ✅

dog = {
    kind: true,
    weight: 10,
}; // ❌ - kind should be a string