We may find ourselves defining the same Type in different places, which is not ideal, considering all the bad things we often hear about code duplication, but what can we do? The answer to that is Type Aliases.
TypeScript allows us to reuse certain types by defining them the same way we would otherwise define a variable or a function, and that’s done through Type Aliases.
What Is a Type Alias?
Simply put, aliases are a way for us to declare certain types as Type Aliases so that we can reuse them in multiple other places.
Type Aliases may store, but are not limited to:
- Primitives
- Objects/Records
- Arrays
- Intersections
- Unions
- Generics
- Other Type Aliases
You can read more about the types available to us on the TypeScript Official Docs.
Type Aliases Syntax
The syntax of a Type Alias would look something like this:
type MyNumber = number;
const x: MyNumber = 10;
const y: MyNumber = '10'; // Will throw error
type MyArray = Array<number | string>;
const arr: MyArray = [10, '12', 17];
const arr2: MyArray = [[arr, 'x']] // Will throw error
type MyObject = Record<string, number>;
const obj: MyObject = { 'key': 12 };
const obj2: MyObject = { 'key': '15' }; // Will throw error
type ObjectWithArrayValue = Record<string, MyArray>;
type ObjectOrArray = Record<string, any> | Array<any>;
type MyGenericType<T> = Array<T>;
const genericNumbersArr: MyGenericType<number> = [12, 14];
const genericStringsArr: MyGenericType<string> = ['12', 14]; // Will throw error
As you may notice, we have defined Type Aliases inside others so that we can reuse types across different definitions as we please. This dramatically improves the benefit we can harness from using Aliases in our TypeScript applications.
As you would expect, we can also export them, thus needing to define them once in the root of our project/application and use them whenever and wherever needed.
Summary
Although a rather short read, I hope you’ve enjoyed it and got a better understanding of what Type Aliases are, what they are used for, respectively the benefits they bring to the table, as well as how we would use them in combinations with other types.
Feel free to let me know whether I’ve left something important out, or if you have any feedback on this article by leaving a comment using the section below.
Cheers!
💬 Leave a comment