Learning typescript
Recently, I have changed up my team and moved to a team which is extensively using typescript language. So, naturally I have to learn it up. In this post I would be discussing about my learnings:
What is Typescript?
Installation
npm install -g typescript
tsConfig.json File
Inside compiler options you can put a lot of fields according to your needs. Check them from here.
Data types:
let name = "hello"let name: string = "hello"
So, ideally both variables hold the same value but in the first case typescript would be able to infer string data type using its type inference. But for the sake of more readability, I generally prefer to use the 2nd way. But yeah my point was typescript provides type inference.
We have talked about let in our last example, but we can also use a varible type named const which makes values inside the variable as immutable.
const name: string = "hello"
There are other datatypes also which typescript can offer void, null, undefined, never, any. So, Let's explore a bit more about these types I have seen these types quite a lot of times but found it bit difficult to understand it.
void: This is used for functions which are not returning any value.
null: Null is used to define intentional absence of an object from variable.
undefined: It defines uninitialized variables.
let name: string | number
Below example allows the type of name to be as either string or an number. If we try to assign something else to it would throw an error.
Functions:
function testFunction(p:string, q:number): void{
...
}
testFunction is the name of the function with return type as void and p,q as input parameters of type string and number respectively.
There is another way also to define function
let functionName = (p:string,q:number)=>{}
functionName ("hello",2)
Interface:
interface Employee{name: string,id: number}
Export and Import statements typescript:
These statements are used to export and import classes, interfaces, function, variables from modules. From module just use export statement to export module.
export class Name {}
export interface Employee {}
or there is another way to do it, use:
export {Name, Employee};
For import just follow this syntax:
import {Name, Employee as Person } from './person'
There is also a concept of relative vs non-relative referencing it is recommended to use relative referencing when module is created by and absolute referencing when module is imported/downloaded. If inside the import path we supply absolute path then typescript would look into node_modules package.
Comments
Post a Comment