Skip to main content

Typescript

Key differences from JS​

  • explicit declarations of data types
  • null or undefined
  • typeof to check data types
const test: number = 0;
if(test typeof number){
console.log("number")
}
  • keyof - gets all the keys from an object

Unique Data types:

  • unknown
  • `never

Access modifiers

  • readonly

Other concepts​

Inheritance or extension​

type Person{
name: string
}

type Employee = Person & {
employeeNumber: number
}

optional​

type Person{
name?: string | null
}

not-null​

type Point = {
name: string;
};

const p = Point({ name: "masd" });
console.log(p!.name);

interfaces​

types assertion​

type Square = {
size: number;
};
type Shape = Square | Rectangle;

function isSquare(shape: Shape): shape is Square {
return "size" in shape;
}

function area(shape: Shape) {
if (isSquare(shape)) {
}
}

Function Overloading​


function hello (test: string)
function hello (test: number)
function hello(test: string | number){
if(test typeof string){
}else if(test typeof number){
}
}

Using types​

type Add = {
(a:number, b: number): number,
(a:number, b:number, c: number): number,
}

const add: Add = (a: number, b: number, c?:number) {
return a+ b + (c != null ? c :0)
}

Abstract classes​

Dictionary​

type Person = {
email: string;
};

type Dictionary = {
[email: string]: Person | undefined;
};

const people: Dictionary = {
mel: { email: "blah" },
};
  • Access modifiers
  • Static properties
  • Abstract classes
  • Constructor
  • Generics

Types versus Interface

Types:

  • Unions
  • Intersections
  • Shorthand Functions
  • Advanced Type Functions Interfaces
  • Declaration Merging
  • extends

Setup

  • see React Testing Library#Pitfalls

Migrating from JS to TS

Steps​

  • Add libraries on Package.json
"@types/jest": "^27.4.1",
"@types/node": "^17.0.27",
"@types/react": "^17.0.47",
"@types/react-dom": "^17.0.17",
  • remove any specialized config files like: jsconfig.json
  • Add tsconfig.json
  "compilerOptions": {
"baseUrl": "./src",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
  • create a TS file with reference to react-scripts

react-app-env.d.ts

/// <reference types="react-scripts" />

Jest

react-testing library typescript jest