Typescript - Beginner Guide to type keyword with example

In this short tutorial, you are going to learn about type keyword in typescript with examples

Type is an keyword in typescript, used as an alias for existing or custom types.

type keyword examples

Following are example

How to declare a type nullable

Let us declare Employee Interface in ts file

interface Employee {
  name: string;
  id: number;
  salary: number;

Create an empty typed array of an interface or class

Employee object holds different types of data.

Using generics type declaration

First, array variable can be declared with generic array of Employeeby assinging empty array

let employees: Array<Employee> = [];

Thus,create a variable stores empty typed array

type assertion

type assertionis like assigning object of one type to variable. This will have no performance impact at runtime. however, It can be used to avoid errors at compile time.

this can be achieved with two syntax, first as syntax and second is angle-bracket syntax

The following is an example for creating empty typed array with as syntax

let empArray1 = [] as Employee[];

The above syntax can also be written with angle-bracket syntax as follows

let empArray = <Employee[]>[]; 

Both are equal in terms of usage and performance.

Array constructor

Finally, array constructor are generic usage and used by every developer. It uses new operator to create an empty array.

let empArray = new Array<Employee>(); 
let empArray: Array<Employee> = new Array<Employee>();

It looks good in readability, however performance impact as creating an reference in memory.

How to create empty typed string array with examples

There are many ways typed string array’s can be created with following syntaxes

let emptyStringArray: string[] = [];
let emptyStringArray1 = new Array<string>(); 
let emptyStringArray2: Array<string> = new Array<string>();

Create and initialize typed empty objects in an array

In this example, we are going to create an non empty array with object data is empty or default values.

let us declare an interface for User

interface User {
  name: string;
  id: number;
  password: string;

Following is an example with array initialized with three empty user objects. Partial in typescript allows you to construct object with optional fields Partial<User> return User with optional id,name and password

users: Partial<User>[] = [{}, {}, {}];

And other option is to manual set values for each object with default values of an object

users1: User[] = [{ id: null, name: null, password:null }{ id: null, name: null, password:null }]


In this tutorial, you learned different ways to creating an typed empty array, and also how to create an array with empty objects.

Please subscribe for new posts.

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.