TypeScript is a superset of JavaScript that adds:
- Static Typing
- Interfaces
- Classes
- Compile-time Error Checking
- Modern ES Features
TypeScript code is compiled into JavaScript using:
tsc filename.ts| JavaScript | TypeScript |
|---|---|
| Dynamically Typed | Statically Typed |
| Runtime Errors | Compile-time Errors |
| Hard to Debug | Easy to Debug |
| No Interfaces | Supports Interfaces |
β Large Scale Applications β Code Maintainability β Better IntelliSense β Refactoring
let id: number = 101;
let name: string = "Raushan";
let isActive: boolean = true;
let data: any = 10;
let list: number[] = [1,2,3];
let tuple: [number, string] = [1,"Hello"];let value: any = 10;
value = "Hello";let userInput: unknown;function greet(): void {
console.log("Hello");
}function error(): never {
throw new Error("Error");
}let num = 100; // inferred as numberfunction add(a:number, b:number): number {
return a+b;
}function show(name:string, age?:number){}function greet(name:string="Guest"){}interface Employee {
id:number;
name:string;
}
let emp:Employee = {
id:1,
name:"John"
}type User = {
id:number;
name:string;
}let id: number | string;type Admin = User & {
role:string;
}enum Role {
Admin,
User,
Guest
}class Person {
name:string;
constructor(name:string){
this.name=name;
}
}- public
- private
- protected
- readonly
function getData<T>(value:T):T {
return value;
}export class Test{}import {Test} from './test';let value:any="Hello";
let length:number=(value as string).length;function Log(target:any){}| Interface | Type |
|---|---|
| Used for Object Structure | Used for anything |
| Extendable | Flexible |
| Less Complex | More Powerful |
{
"target": "ES6",
"module": "commonjs",
"strict": true,
"outDir": "./dist"
}β Interfaces β Generics β Union Types β Enums β Type vs Interface β Any vs Unknown β Access Modifiers β Type Inference β Modules β Decorators β tsconfig.json