Getting started with TypeScript

Getting started with TypeScript

ยท

5 min read

In the official docs of TypeScript it says TypeScript is JavaScript with syntax for types but it assumes we should know the meaning of types. For keeping things simple let's say TypeScript is a layer on top of the JavaScript. If you scratch the layer you will find JavaScript inside.

But why TypeScript is a layer? It is because when we write TypeScript code in editor it gets complied and all the TypeScript stuff is gone and what is left behind is plain JavaScript which can be understood by your browser.

TypeScript makes the life of developers very much easier. I always wanted to learn it but was always scared thinking it would be a very complex thing to understand. Finally, when it was forced upon me I had to learn and explore. I have to say that once you understand even the basics of TypeScript you will also understand why it makes your life easier.

Why TypeScript?

Yes, even I had a thought that why should I go through the TypeScript when I know it gets converted to JavaScript. Doesn't writing code straight in JS will make more sense. But let me tell you TS(TypeScript) is not there to make things complicated but to help you not make mistakes.

When you will write the code you will see how it catches serious and silly mistakes making it underlined by red. Also in a large codebase, it makes it easier for developers who will see the code 3 months later. And what to say about auto-completion it is just like icing on the cake.

Installation

You can install TS using npm you can either install it in each project so install it globally.

npm install -g typescript

To confirm the installation check the version of the TS

tsc -v

Exploring Types

In his book, Programming with Types, Vlad Riscutia defines types as follows:

A type is a classification of data that defines the operations that can be done on that data, the meaning of the data, and the set of allowed values Typing is checked by the compiler and/or run time to ensure the integrity of the data, enforce access restrictions, and interpret the data as meant by the developer

Basically from types TS comes to know that "Hello World" is string 123456 is a number etc

Types are very fundamental to programming. Even JavaScript has types but the only difference is it is weakly typed.

Now what it means is even though you create a variable and assign a value of a certain type(string or number), you can switch types in the code.

let val = "I am String"; 
val = 1234

But TS is strongly typed. This means that once you assign a certain type you will have to use only that type throughout.

let val = "I am String"; 
val = 1234 //Type 'number' is not assignable to type 'string'.

Lets go through the different types :

Number

let num: number = 123;

Boolean

let yes:  boolean = true;

String

let name: string = "John Doe"

Array

let nums: number[] = [1,2,3]

Tuple

let person: [number, string, boolean ] = [1,"John",true]

Union

let ID : string | number = 22

Function

function addNum(x: number, y: number): number {
    return x+y
}

If the function is not returning anything we can use the void keyword

function response(message: string | number): void {
    console.log(message);    
}

It doesn't stop here we can get deeper and define the shapes of objects. For example, if a person is having a name and age we can make sure it's of type string and number

type User {
   name: string
   age: number
}

const user: User {
  name: "John Doe"
  age : 23  
}

Sometimes we may not be sure of some properties in the object. ie it can be optional properties in that case we can use "?". So we don't get any error if that property is not present.

type User {
   name: string
   age?: number
}

To execute the TS file you will have to run this command on terminal

tsc index.ts

Interfaces

It is another way of using a type of object. The syntax is similar too.

interface UserInterface {
    name: String
    age?: number
}

The difference between interface notation and type notation is, interfaces are extendable while types are not.

Generics

Generics offer a way to create reusable components. It provides a way to make components work with any data type and not restrict to one data type.

function getArray<T>(items: T[]): T[]{
    return new Array().concat(items)
}

let numArray = getArray<number>([1,2,3,4])
let strArray = getArray<string>(["John","Joe"])

Here getArray() function can be used with number or string types.

Using in React

The best part of TypeScript is it is used in all major libraries and frameworks. Let take the example of React Library.

In React when passing props to another component we can specify the props in which we are expecting, thereby removing production errors.

Let take the example of header.tsx component in which it is excepting title and color

  return (
    <div className="App">
      <Header title = "Todo" color="blue" />
    </div>
  )

So in the Header.tsx the props would be expecting the title of type string and color of type string.

export interface Props {
    title : string
    color?: string
}

const Header = (props: Props) => {
    return (
        <div>
            <h1 style={{color: props.color ? props.color : "red"}}>
                {props.title}
            </h1>            
        </div>
    )
}
export default Header

As you see we created an interface called Props which is an object which assigns the title and age of the type string.

And if in case I forget to pass props the TS compiler will straight away shoot an error of

 Property 'title' is missing in type '{ color: string; }' but required in type 'Props'.  TS2741

Conclusion

Well we come to the end of this blog, TS will take a bit of extra work in terms of writing codes but this little extra time we invest will really same some big-time in the future. We covered the very basic concepts of TS but I highly recommend you to give a try and use it in your side projects.

Refrences

Official TS Handbook

TypeScript Deep Dive

TypeScript Crash Course 2021

Happy Codding..!!๐Ÿ™Œ๐Ÿฝ

Did you find this article valuable?

Support Vishak Amin by becoming a sponsor. Any amount is appreciated!

ย