Man

Development & AI | Alper Akgun

TypeScript notes

September, 2023

TypeScript notes


npm install typescript --save-dev
tsc ts1.ts --out /dev/stdout | node // Convert a ts file to JS and execute

console.log("Hello, World!");

// Declarations
let flying: boolean
let running: boolean = false

console.log({ running, flying })

// Basic types
let chameleon: any;
let voyd: void;
let firstName: string = "Joe";
let age: number = 21;
let nul: null;
let notdefined: undefined;
let numberOfStars: bigint;
let key: symbol;

console.log({
  voyd,
  firstName,
  age,
  nul,
  notdefined,
  numberOfStars,
  key,
});

// Advanced types
let names: string[] = ['Joe', 'Jane', 'Alice'];
let name_age: [string, number] = ['Joe', 21];
let pairs: [string, number][] = [['Joe', 21], ['Jane', 22]];
let state: string | null | undefined = 'S';
console.log({
  names,
  name_age,
  pairs,
  state
});


enum Color {
  Red,
  Green = 3,
  Blue,
}
let r: Color = Color.Red;
let c: Color = Color.Green;
let b: Color = Color.Blue;
console.log({
  r,
  c,
  b,
});

let len: number = "Alice".length
console.log({ len })

function areaOfCircle(r: number): number {
  return Math.PI * r * r;
}
let r: number = 2;
console.log({ r, area: areaOfCircle(r) });

interface User {
  readonly name: string,
  age: number,
  optional?: boolean
}

let user: User = { name: 'Alice', age: 22 };
console.log({ user });

type Name = string | string[];

// intersection
interface OneType {};
interface AnotherType {};
type MyType = OneType & AnotherType;

function getUser(callback: (user: User) => any) {
  return user;
}

class Rectangle {
  x: number;
  y: number;
  static instances = 0;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

class Square extends Rectangle {
  constructor(x: number) {
    super(x, x);
  }
}

class Eater {
   name: T;
   constructor(name: T) {
     this.name = name;
    }
 }

let cat = new Eater('Tom');
console.log(cat.name);