TypeScript

JavaScript

+

static types

=

TypeScript

function add(a, b) {
  return a + b;
}

JavaScript

JavaScript + types

function add(a: number, b: number): number {
  return a + b;
}
TypeError: Cannot read property 'name' of undefined

TypeError: undefined is not a function

Why?

Autocomplete

Faster feedback loops

Demo

const a: number = 1;
const b: number = 1.5;

const c: string = 'hello';
const d: string = "world";
const e: string = `${c} ${d}`;

const f: boolean = true;
const g: boolean = false;

const h: object = {};

Basic types

const myArray: number[] = [1, 2, 3];

const myTuple: [number, number] = [800, 600];

Arrays and tuples

Type alias

type Point = [number, number];

const myPoint: Point = [35, 100];

type Bounds = [number, number];

const myBounds: Bounds = myPoint;
type Person = {
  name: string,
  age: number
};

interface Person2 {
  name: string;
  age: number;
}

Object types

function siHei(person: Person): void {
  alert(`Hei ${person.name}!`);
}

function siHei(person: { name: string, age: number }): void {
  alert(`Hei ${person.name}!`);
}
type Numberish = string | number;

type Ternary = 'true' | 'false' | 'maybe';

type PersonFromMessyAPI = {
  name: string | undefined | null,
  age: number | undefined | null,
};

type Action
  = { type: 'SET_VALUE', newValue: number }
  | { type: 'INCREMENT' }
  ;

function doWithAction(action: Action) {
  if (action.type === 'INCREMENT') {
    action.newValue // Kompileringsfeil
  }

  if (action.type === 'SET_VALUE') {
    action.newValue // OK
  }
}

Union types

enum Ternary {
  FALSE,
  TRUE,
  MAYBE
}

enum Ternary {
  FALSE = "FALSE",
  TRUE = "TRUE",
  MAYBE = "MAYBE"
}

Enums

type Drivable = {
    maxSpeed: number,
}

type Crashable = {
    isTotalWreck: boolean,
}

type Turnable = {
    turnRadius: number,
}

type Car = Drivable & Crashable & Turnable;

const car: Car = {
    maxSpeed: 200,
    isTotalWreck: false,
    turnRadius: 30,
};

Intersection types

const foo: any = 5;

foo.toUpperCase();

foo.this.will.fail;

function meh(bar) {
    bar.also.fails();
}

any

function throwError(message: string): never {
    throw new Error(message);
};

never

function identity<T>(t: T): T {
    return t;
}

Generics

type Nullable<T> = { [P in keyof T]: T[P] | null }

Oppgaver

github.com/bekk/typet-javascript-workshop

Typescript

By Erik Vesteraas

Typescript

  • 612