TypeScript Enum, Array and Tuples types

Note Statistics

Note Statistics

  • Viewed 54 times
Tue, 12/29/2020 - 19:45

Here is a short list of complex/composite basic types

Enum

Use to represent a set of possible values.

enum Color = { Blue, Green, Red}; // 0, 1, 2
enum Color = {Blue = 5, Green = 10, Red = 20 }; // 5, 10, 20

const favoriteColor: Color = Color.Green;
console.log(favoriteColor); // 5

let myColorString = Color[favoriteColor]; // Green

Array

Array are a list of related objects. They can be defined in two ways

let fruits: string[] = ['apple', 'mango'];

or using generics

let fruits: Array<string> = ['apple', 'mango'];

TypeScript array requires a type for the elements it can contain. Here is an example array that can contain any item type.

let anythingList: any[] = [0, false, 'hello'];

Tuple

A tuple is an extension of an array that allows the definition of types at index level. Let's look at examples

let myTuple: [number, string] = [32, 'John Doe'];
let age = myTuple[0]; // 32
let fullname = myTuple[1]; // John Doe

// Other items of the array can be numbers or strings

myTuple[2] = 23;
myTuple[4] = 'Banna Street';
myTuple = 1;// error
Authored by
Tags