Onyee Peace
onyeePeace

onyeePeace

Unions & Type Aliases in TypeScript

Onyee Peace's photo
Onyee Peace

Published on Dec 28, 2020

2 min read

Description

Unions

Unions are used to combine more than one data type to be used on a variable. This is how it is done;

// This can be used to declare multiple data types in a variable
let combined: (string | number)[] = [];
//When using unions on arrays, it needs to be enclosed in parenthesis.

combined.push('hello', 2);
console.log(combined); //result will be an array with 2 items: hello and 2.

//union type on variables
let uid: string | number; //this means the uid variable can either be a string or a number
uid = 'me'; 
uid = 1;
console.log(uid); //result will be 1.

Type Aliases

These are used to store type specifications, eg: union types, so that they can be reused to avoid repeating code.

//Without using type aliases;
const details = (uid: string | number, item: string) => {
    console.log(`${item} has a uid of ${uid}`)
}

const greet = (user: {name: string, uid: string | number}) => {
    console.log(`${user.name} says hello`);
}

//Using type aliases;
//type aliases can be made like this
type StringOrNumber = string | number;

const details = (uid: StringOrNumber, item: string) => {
    console.log(`${item} has a uid of ${uid}`)
}

const greet = (user: {name: string, uid: StringOrNumber}) => {
    console.log(`${user.name} says hello`);
}

//it can also be written for the object in the greet function like this;
type objWithName = { name: string, uid: StringOrNumber};

const greet = (user: objWithName) => {
    console.log(`${user.name} says hello`);
}
 
Share this