Typescript

As explained by

Typescript

  • npm i -g typescript

  • tsc -v

  • tsc index.ts

  • tsc index.ts --watch watchmode

  • tsc --init → create tsconfig.json

  • tsconfig.json → compiler settings

{
    "compilerOptions": {
      "target": "es3",
      "watch": true,
      "lib": ["dom", "es2017"]
    }
}

Typing

let test: number;

test = 23; // valid
test = "23" // invalid
let test = 23;
type Style = 'bold' | 'italic' | 23;

let font: Style;
font = "something"; // invalid
font = "bold"; //valid

Interfaces

interface Person {
  first: string;
  last: string;
}

const person: Person = {
  first: "Jeff",
  last: "Delaney"
}
interface Person {
  first: string;
  last: string;
  [key: string]: any //allow further attributes
}

Functions

function pow(x,y){
  return Math.pow(x,y);
}
function pow(x:number ,y:number): number{
  return Math.pow(x,y);
}
  • we can use optionals

function calculateTax(income: number, taxYear?: number):number{
  if (taxYear < 2022)
    return income * 1.2
  return income * 1.3
}
  • provide values for potentially undefined object

function calculateTax(income: number, taxYear?: number):number{
  if ((taxYear || 2022)) < 2022)
    return income * 1.2
  return income * 1.3
}
  • or provide adefault value

function calculateTax(income: number, taxYear = 2022):number{
  if ((taxYear || 2022)) < 2022)
    return income * 1.2
  return income * 1.3
}

Arrays

const.arr: number[] = []
arr.push(1)

Enums

enum Size { Small, Medium, Large }
enum Size { Small=1, Medium, Large }
enum Size { Small='s', Medium='m', Large='l'}

If we use const enum the source will be optimized.

Objects

let employee = {
  id: number,
  name?: string
  } = {id: 1}
employee.name = "Mosh"
  • better withou optionals

let employee = {
  id: number,
  name: string
  } = {id: 1, name = ''}
employee.name = "Mosh"
  • read only attributes

let employee = {
  readonly id: number,
  name: string
  } = {id: 1, name = ''}
employee.name = "Mosh"
let employee = {
  readonly id: number,
  name: string,
  retire: (date: Date) => void
  } = {
    id: 1,
    name = '',
    retire: (date: Date) => {
      console.log(date)
    }
  }
employee.name = "Mosh"

Enhancements

  • typeAlias

type Employee = {
  readonly id: number,
  name: string,
  retire: (date: Date) => void
}

let employee: Employee= {
    id: 1,
    name = '',
    retire: (date: Date) => {
      console.log(date)
    }
  }
employee.name = "Mosh"
  • unionTypes

function kgToLbs(weight: number | string ){
  // narrowing the uniontype into a more specific type
  if (typeof weight == "number")
    return weight*2.2
  else
    return parseInt(weight)*2.2
}

kgToLbs(10) // valid
kgToLbs("10 kg") // valid
  • intersectionType

type Draggable = {
  drag:(): => void
}
type Resizeable = {
  resize:(): => void
}
;
type UIWidget = Draggable && Resizeable;

let textBox> UIWidget ={
  drag: () => {}
  resize: () => {}
}
  • Literal

let quantity: 50 | 100 = 50;
type Quantity = 50 | 100;
type Metric = "cm" | "inch";

let quantity: Quantity = 50;
  • Null and undefined values

function greet(name: string){
  console.log(name.toUpperCase());
}
greet(null) // invalid because of config strictNullChecks: true|false
function greet(name:string | null | undefined){
  if (name)
    console.log(name.toUpperCase());
  else
    console.log("Hola!")
}
greet(null) // valid because of our unionTypes
type Customer = {
  birthday: Date
};

function getCustomer(id: number): Customer | null | undefined{
  return id=== 0? null: { birthday: new Date() };
}

let customer = getCustomer(0)
if (customer !== null && customer !== undefined)
  console.log(customer.birthday);
type Customer = {
  birthday: Date
};

function getCustomer(id: number): Customer | null | undefined{
  return id=== 0? null: { birthday: new Date() };
}

let customer = getCustomer(0)
// Optional property access operator
  console.log(customer?.birthday);
  • Optional element access operator

  • Optional call operator

Optionals

  • ?

type MyList = [number?, string?, boolean?]
const arr:MyList = []

Generics

Yea.

TypeScript Documentation

export class Statistics {
  /**
   * Returns the average of two numbers.
   *
   * @remarks
   * This method is part of the {@link core-library#Statistics | Statistics subsystem}.
   *
   * @param x - The first input number
   * @param y - The second input number
   * @returns The arithmetic mean of `x` and `y`
   *
   * @beta
   */
  public static getAverage(x: number, y: number): number {
    return (x + y) / 2.0;
  }
}