User Defined Data Types in TypeScript With Example

We have seen primitive data type in typescript tutorials, now lets have a closer look at user defined data types in typescript.

  1. Array : Array datatype allows user to store different data types values. We can store string, numbers , boolean values in combination sequentially in array.
let arrayVariable: string[] = ['Apple', 'Orange', 'Banana'];
//altenative declaration
let arrayVariable: Array<string> = ['Apple', 'Orange', 'Banana'];
//Both are same

2. Enum : Enum data types supports declaration of different named constants. Let’s say we should have data structure which should hold week days only. In that can we can use enum.

enum WeekDays {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}

3. Tuples: Tuples allows us to declare an array with known datatype of each elements within it. Lets say we want to create a student record which will hold name,roll no, address.
So sequence of record will be string, number, string. We can not store values in any other sequence than this.

let student : [string, number,string];
student  = ["Ramesh",1,"My Address"]; // Initialisation, OK
student  = ["Ramesh","My address",1]; // Error as sequence not followed 

There are also 2 more custom data types classes and interfaces which we will cover in deep in their respective articles.