Typescript tutorials: union types and literal types in typescript

Bootstrap Jun 13, 2019

Let’s try to answer the most asked interview question of typescript

What are union and literal types in typescript? one of the most asked typescript
interview questions

In this typescript tutorial, we will see what
union types and literal types in typescript are

The problem without union type

with typescript now we have a better control over our code, and we can express
the things in more typed manner but some time we need a different behavior lets
say I have an API which sends me data and sometimes its send me an object and
some times a message in false case like not found or lousy request in that cases
I can not have one type of datatype right, so we have to use any type over their

function fetchrecords() {

// we make our api call and in success call back 
      let data:any = result//result is the return from the api

the code above looks working but if we dig more inside it we are moving away
from the essential behavior of typescript which is its type of support
now we have two problems one is we want our type to be dynamic like it can be
string also and a costume type lets say employee also
moreover, the other
is we want our data to be of the proper type (static type also)

Union type in Action

to solve this kind of problems we have union types in typescript
so let’s
see how our code looks when we apply union types to it

function fetch records() {
// we make our API call and in success call back 
      let data:Employee | string = result
//result is the return from the API      //

so now the data can be of employee type or string type, and no other type is
valid other than these two types

Literal Types


now let’s take it a step ahead and see what literal types in typescript are

let’s say I have a function

function getJuice(fruit:string){
    let fruitjuice = ''
    //we make juice of it 
    return fruitjuice;

now the above function is simple to understand it takes a fruit makes its juice
and return the fruit juice
now let’s call it with some fruits


now in the above code, you will see that apple and mango are valid fruits but
the computer is not, and we don’t have any restriction as our function accepts
string we can pass anything to it
however, it’s wrong right we need a way
for the user only to enter valid items from a group of items lets to say the
fruit can only be ‘Apple,’ ‘Mango,’ ‘Orange.’
moreover, all other values
passed should be invalid in that case we use string literals as we are using
literal for string type
so now let’s see how our code will look like

Literal types in action

function getJuice(
    let fruitjuice = ''
    //we make juice of it 
    return fruitjuice;


now the last line in the code ‘getJuice(computer’)’ will throw an error

that is literal types
I hope it made your concept clear on what is literal
and union types

Thank you