Skip to content

Instantly share code, notes, and snippets.

@mirashif
Created August 28, 2020 13:51
Show Gist options
  • Save mirashif/1f5ce88df59a73c84cd8d4ecdb8b251c to your computer and use it in GitHub Desktop.
Save mirashif/1f5ce88df59a73c84cd8d4ecdb8b251c to your computer and use it in GitHub Desktop.
TypeScript basic syntax to get started building apps.

Types

let a: number,
  b: boolean,
  c: string,
  d: any,
  e: number[] = [1, 2, 3],
  f: any[] = [1, true, 'a', false];

Enumerated type

enum Color {
  Red = 0,
  Green = 1,
  Blue = 2,
  Purple = 3,
}
let color = Color.Blue;

Type assertions

let message;
message = 'abc';

let length = (<string>message).length;
let altWay = (message as string).length;

Interfaces

interface Vector {
  x: number;
  y: number;
  z: number;
  draw: () => void;
  update: (x: number, y: number, z: number) => void;
}

Class

  • Constructor initializes _x, _y variables. Question mark (?) declares the variables as optional.
  • Access modifiers: public (default), private, protected.
  • Using getters and setters method to provide more control.
  • Exporting module Point class.
export class Point {
  constructor(private _x?: number, private _y?: number) {}

  draw() {
    console.log(`x = ${this._x}, y = ${this._y}`);
  }

  get x() {
    return this._x;
  }

  set x(value) {
    if (value < 0)
      throw new Error('Value cannot be less than 0.')

    this._x = value;
  }
}
  • Importing Point class and using the methods.
import { Point } from './point';

// Variable type of point is Point. 
// Alternative way
// let point: Point = new Point(1, 2);
let point = new Point(1, 2);

point.draw(); // x = 1, y = 2

point.x; // 1

point.x = 3; // sets x = 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment