DEV Community

Cover image for Typescript - Basics and use cases
Junaid
Junaid

Posted on • Edited on

Typescript - Basics and use cases

Typescript as we all know is the what was missing in javascript from ages - A static type checking system since javascript itself is a weakly typed language

With the help of typescript we can give type-safety to our js codebases like react.

So lets get started with the basics of typescript

First of lets cover the types of variables

A variable in javascript can be of these types

  • string
  • number
  • boolean
  • undefined *
  • null *
  • object

So lets cover them one by one

If a variable is going to be a string we can simple put it inclusively
item : string
This means that item is strictly going to be a string only
similarly with the other types e.g
item : number. / for number
item : boolean / for boolean

now these are the basic types , but for props that can be grouped together how do we create some thing that shows a group of types together

That is where type and interface comes into effect

Both are used to create a group of types that a component is going to get

e.g

type inputTypes{
value:string,
placeholder:string,
type:string
}

Similarly can be done with interface as well but there are some differences

  • object type can be shown in interface but not in type
  • interface with same name in the same file gets merged but that is not for types - for them its just an error

now lets talk about creating types for objects and functions

Objects

Objects has two things to be taken care of i.e
Key part and the value part
so for objects we can set type as like this

[v:string]:string

you can use all the basic types as key and value types here

this means the key is going to be a string and the value is also going to be a string

Functions
Now with functions there are also two parts to it i.e

  • Parameters that it is going to be getting
  • and the return type that the function is going to be returning

So an example is going to be like this

type functionProps{
name:string,
age:number,
isAboveThirty:boolean}

function getAgeSection({name,age,isAboveThirty}:functionProps):string{
if(isAboveThirty){
return 'the person is above thirty'
}else{
return 'He is below thirty'
}
}

what this means is the function is going to accept the types which are functionProps and the return type is going to be a string

If u don't provide a return type it is going to either infer the type from whatever u returned from the function , or if you don't return anything at all it will set it to void

These are just the basic types just to get you started with typescript

In the next post i will share how to use typescript in a react app with some advanced types like click events ,input events

Top comments (0)