Explore basic types of TypeScript
Typescript is an object-oriented Programming language that is built on top of JS with extra features.TypeScript is like an extension or “superset” of JavaScript.
# What's wrong with javascript?
- not suitable for large applications
- lacks strong typing
- weird inheritance, unfamiliar syntax
- only errors during runtime
- suffers type correction
# Benifits of TypeScript
- Supports older browser
- Type Safety
- increase your productivity
- less bugs and less testing
# Drawbacks of using Typescript
- Type complexities
- Limited Libray Support
- Over Engineering
- Migration challenges
#Install TypeScript and node version
First of all, you download node js from node js website. if you want to switch your node version you should use nvm(node version manager). if you do not know how to install it you can read it.https://www.freecodecamp.org/news/node-version-manager-nvm-install-guide/
// any version download
nvm install node_version
// nvm use command
nvm use node_version
# TypeScript Install
npm install -g typescript
# Write your first TypeScript Program
create a file and ensure that the file extension is ts.
ts package.json file initialization cmd = tsc -init
ts file in root dir (pakage.json)
js file in output dir (pakage.json)
live runnig tsc file cmd = tsc -w
# Explict and union types
// Normal variable
let a : string | number
//array
let b : (string | number)[] = []
// object
let c : object
let c : {
name : string,
age : number
}
# Dynamic Type
let a : any
let c : {
name : string,
age : number
}
# How to use the function
let myFunc : Function
myFunc= (a : string, b? : string, c : string = 'string') : string=>
{
}
# Type Aliases — make your own type
type typeName = string | number
type typeName2 = {name : string; age : number}
# Working with class
class Player {
name: string;
age: number;
constructor(n: string, a: number) {
this.name = n;
this.age = a;
}
}
const sakib = new Player("sakib", 36);
const tamim = new Player("tamim", 35);
const musfiq = new Player("sakib", 37);
# Access Modifier
public
private
readonly
class Player {
constructor(
private name : string,
public age : number,
readonly anything : void
) {
this.name = n;
this.age = a;
}
}
# Module System
tsconfig.json
- “target”: “es6”
- “module”: “ES2015”
index.html
script tag type=’’module”