Using Type Aliases Instead Of String literals In Typescript

notdennis
2 min readJan 24, 2021

introduction

Type aliases in typescript are used to create reusable alias for any typescript types eg strings, numbers, etc which accomplishes the goal of DRY(don't repeat yourself) in coding while String literals allow use to use string as a type.

Using string literals

we can use string literals to create types, lets create a variable “animal” instead of assigning the variable we create to the traditional typescript type eg string we assign it to a particular value “dog” as its type.

let animal:"dog"animal = "dog"   // ok//
animal = "pig" // compiler compalins //

in the code snippet above the compiler would complain if we try to assign “animal” to any other value that is not “dog”.

string literals can even be more dynamic and powerful when we use it alongside typescript union type which is used to define a type that can be more than one.

let animal:"dog" |"pig"animal = "dog"   // ok//
animal = "pig" // compiler is happy //

from the code snippet above you would notice that the compiler didn't throw any error because we used the union type to make it accept both “dog” and “pig” respectively. The problem with a literal string is that we can’t use it as a type for other variables henceforth it's not reusable compared to type alias, interface, etc.

Using Type ALiases

As a programmer our first goal while writing code is not to repeat the same block or line of code over and over again, well type alias helps us achieve that while writing typescript.

Type Alias creates a new name for a type or it creates a name to refer to a type, it's similar to interfaces but can house any type like string, number, tuple, union, function, etc.

type animal = "dog" |"pig"const pet1:animal = "dog"   // ok//
const pet2:animal = "pig" // compiler is happy //

compared to string literals you can use the type “animal” anywhere in your code.

Referencing other types with keyword Type

type num = 1 | 2; // number
type bool = true | false; // boolean
type obj = {a: 1} | {b: 2}; // object
type func = (() => string) | (() => void); // function

conclusion

In this article, we discussed the key difference between string literals and type alias in typescript and when to use which depending on your use case.

happy coding!

--

--

notdennis

Dennis is a Frontend Developer with demonstrated 3 years+ of experience in building and maintaining pixel-perfect web and mobile applications,.