Type Aliases
Type Aliases in TypeScript allow you to create a new custom type name that can be reused throughout the code in other words a name for any type. Type Aliases are used to create custom names for primitives, arrays, unions, tuples, objects, and function signatures.
Syntax:
type TypeAliaseName = anyType;
Where:
- type is the keyword used for defining the type
- TypeAliaseName is the name of that type
- anyType is the type you want to declare
Example: This example shows the use of the type alises in typescript.
Javascript
type BookName = string; type BookSerialNum = number; type IsAvailable = boolean; type BookReviews = string[]; // Array type Author = [string, number] // tuple // Object type Book = { book: BookName, serialNum: BookSerialNum, isAvailable: IsAvailable, reviews: BookReviews, authorInfo: Author, } //Union type BookPriceUSA = number; type BookPriceUK = number; type BookPrice = BookPriceUSA | BookPriceUK; // Function signature type DisplayInfo = (arg: Book) => void; let book1: BookName = "Harry Potter and the Philosopher's Stone" let book1Number: BookSerialNum = 1741239 let book1isAvailable: IsAvailable = true let book1Reviews: BookReviews = ['good ', ' nice, 10/10 ', ' excellent '] let book1Author: Author = [' J.K. Rowling', 57] let book: Book = { book: book1, serialNum: book1Number, isAvailable: book1isAvailable, reviews: book1Reviews, authorInfo: book1Author, } const display: DisplayInfo = (arg) => { console.log(arg); } display(book); |
Output:
TypeScript Differences Between Type Aliases and Interfaces Type
TypeScript is an open-source programming language that adds static typing and other valuable features to JavaScript. TypeScript is also known as a super-set of JavaScript. Type Aliases and Interfaces Type are used to create custom types in TypeScript. In this article, we will learn about the Differences Between TypeScript Type Aliases and TypeScript Interfaces type.