Different Typescript types and how to use it

Author
April 06, 2022

In this article i will explain you how to use different typescript types

1. Core Types

Number

In typescript all the numbers are float by default, in javascript or typescript there is no difference between 5 and 5.0 they are all same

const number = 5;
const number2 = 2.8;
Boolean
const boolresult = true;

if (boolresult) {
  console.log("Inside if");
}
Strings
const strresult = "This is string constant variable";

In all the above type typescript uses type inference to decide what type of variable based on the value we have assigned we can also manually define the type as below

const number: number = 5;
const boolresult: boolean = true;
const strresult: string = "This is string constant variable";

2. Object Types

In this example we are just telling typescript object that the variable is of type object

const person: object = {
  name: "Abc",
  age: 50,
  hobbies: ["sdfsd"],
  role: [1, "abc"],
};

In this example we are gonna tell typescript what is the type of properties that typescript object will hold

const person1: {
  name: string;
  age: number;
  hobbies: string[];
  role: [number, string];
} = {
  name: "Abc",
  age: 30,
  hobbies: ["sdfsd", "sdfsdf"],
  role: [1, "abc"],
};

3. Array Types

In this example typescript uses typeinference to detect what type of variable hobbies is

const hobbies = ["Cooking", "Singing"];

In this we have manually tell the typescript that hobbies variable is of type array which holds string value

const hobbies: string[] = ["Cooking", "Singing"];

4. Tuple

Tuple is fixed length and fixed type array in typescript

In this example you would notice that we have define the type inside array this mark that we will have only two element and they will be of type number and string

const role: [number, string] = [1, "abc"];

5. Enum

const ADMIN = "ADMIN";
const AUTHOR = "AUTHOR";
const READ_ONLY = "READ_ONLY";

enum ROLE {
  ADMIN,
  AUTHOR,
  READ_ONLY,
}

console.log(ROLE.ADMIN);

6. ANY Type

Any type when used cancel the type check and can store any type of value inside variable for example

const role: any[] = ["Abc", 1];

7. Union Type

Union type variable helps us where we want any varibale to accept one or more type of values for example

const uniontype: string | number | boolean = "String var";
uniontype = 10;
uniontype = true;

8. Literal Types

const literaltype: "as-text" | "as-number" = "as-text";

9. Type Aliases

In below we have defined a type alias for our union type and we are refeering that alias in the constant variable

type combinable = number | string | boolean;

const combinablevar: combinable = "hello alias";
type User = { name: string; age: number };
const u1: User = { name: "abc", age: 30 };

10. Function Types and Return Types

In this example we have defined function return type as a number

function add(n1: number, n2: number): number {
  return n1 + n2;
}

In this example we have defined function return type as void

function printResult(num: number): void {
  console.log("Hello" + num);
}

In this example we are declaring a variable which is of type function

let functiontype: Function;

In this example we have defined function types but we are specific about what type of argument it will recieve and what will be the return type

function add(n1: number, n2: number): number {
  return n1 + n2;
}
let functiontype: (num1: number, num2: number) => number;

functiontype = add(5, 2);

11. Function callback type

function addAndHandler(n1: number, n2: number, cb: (num: number) => void) {
  const result = n1 + n2;
  cb(result);
}
addAndHandler(1, 2, (result) => {
  console.log("Result", result);
});

12. Unknown type

In unknown type we can store any type of values for example

let unknowntype: unknown;
unknowntype = 5;
unknowntype = "Abc";

The difference between unknown type and any type is you cann’t assign any other type variable to unknow type variable but in case of any you can

let userInput: unknown;
let userName: string;

userInput = 5;

//this will throw error as unknow type can be or cann't be of type string
//but in case of any this will work
userName = userInput;

13 Generic Types

Generic type is a type which is connected with some other type

In this example we have defined generic array type which hold string value

//generic way of defining
const names: Array<string | number | boolean> = [];

//similar to above
const names: sting[] = [];

In this example we have defined a promise of generic type, we are sepcifying that this promise will return number type

const promise: Promise<number> = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(10);
  }, 2000);
});

In this example we are defining a function which has generic type

function merge<T, U>(objA: T, objB: U) {
  return Object.assign(objA, objB);
}

const mergeObj = merge<{ name: string; hobbies: string[] }, { age: number }>(
  { name: "Max", hobbies: ["sdfsd"] },
  { age: 30 }
);