Union types in TypeScript

<Blake†Codez />
1 min readDec 6, 2022

--

Typescript allows us to express a type as a combination of two or more other types. This is known as a union type.

To create a union type, you can combine any types with the ( | ) pipe symbol like so:

function printSomething( something: string | number ) {
console.log(`something = ${something}`);
}

printSomething(7); // something = 7
printSomething('a string'); // something = a string

The printSomething function can accept either a string or a number type to indicate a union type.

Same can apply for a simple variable:

let myType : number | string = 'hello';
myType = 1;

*Note, using these types as union types aren’t very clean ways of writing code, but I guess this can be handy to know. Types should be specific to one type to avoid confusion and scaling properly with other developers. If using a Union type, probably the cleanest way to do it would be to create a type alias like so:

type StringOrNumber = string | number;

function printStringOrNumber(value: StringOrNumber) {
// ....
}

A type alias, similar to a typedef in Dart or C++. It is handy to describe a type and use the type for more sophisticated logic or components.

--

--

<Blake†Codez />
<Blake†Codez />

Written by <Blake†Codez />

I’m a Software Engineering student in Redding, Ca. Love all things Computer Science related, love for journalism, Jesus Christ, and team collaboration projects.

No responses yet