TypeScript has its types and also allows us to write our own custom types.

Core Types

These work on JS and TS.

  1. number - numbers, decimals, negative numbers all come under this type.

  2. string - text.

  3. boolean - true, false.

    Screenshot 2022-10-18 at 11.01.39 AM.png

    Screenshot 2022-10-18 at 11.07.01 AM.png

    Note in the add() arguments we are saying explicitly that the arguments will be number.

    Screenshot 2022-10-18 at 11.10.40 AM.png

    TypeScript is statically typed, which means we define the types of variables and parameters hands on during development.

    Key difference between TS and JS:

    Screenshot 2022-10-18 at 11.16.05 AM.png

    and it is better to fail during development then during runtime.

Type Casting

Screenshot 2022-10-18 at 11.17.34 AM.png

Type Assignment & Type Inference

Screenshot 2022-10-18 at 11.23.25 AM.png

Here you can see below when i am doing const number1 = 5, const number2 = 2.8, etc. I am not assigning any type like I did in the function arguments. This is because of a TS feature called inference. Which means TS does its best to identify the type of the variable. So, it will know that number1 is a number and so on. Now, we can add : number in this as well, but it is not considered to be a good practice since the TS does a pretty good job infering it. Now, there is one condition in which you should do this. Which is when you are not initializing, you do it like this:

Screenshot 2022-10-18 at 11.28.03 AM.png

Screenshot 2022-10-18 at 11.31.16 AM.png

Screenshot 2022-10-18 at 11.31.43 AM.png

Object types

Contain key value pairs. Now consider: