TypeScript

What is TypeScript?

Getting started

Install TypeScript

# npm
npm install typescript --save-dev
# yarn
yarn add typescript --dev

Compile *.ts files to *.js files

# npm
npx tsc
#yarn
yarn tsc

Watch for changes

# npm
npx tsc -w
#yarn
yarn tsc -w

Add TS to a project

cd ~/Workspace/my-awesome-project
tsc --init

Basics

Example

message.toLowerCase()
message()

Problems

Solution

const message = "Hello World!"
message.toLowerCase() // it works
message() // error → This expression is not callable.

Working with the type system

Common types

Type annotations

Type assertions

// using the `as` keyword
const logo = document.getElementById('logo') as HTMLImageElement
// using angle-bracket syntax
const logo = <HTMLImageElement>document.getElementById('logo')

Type aliases and interfaces

Type aliases

type ID = number | string
type Point = {
  x: number
  y: number
}

function printCoords(id: ID, pt: Point) {
  if (typeof id === 'string') {
    console.log(id.toUpperCase())
  } else {
    console.log(id)
  }
  console.log(pt.x, pt.y)
}
…

Interfaces

interface Point = {
  x: number
  y: number
}

function printCoords(pt: Point) {
  console.log(pt.x, pt.y)
}

Types vs. Interfaces

Aspect Type Interface
Can describe functions
Can describe constructors
Can describe tuples
Interfaces can extend it ⚠️
Classes can extend it 🚫
Classes can implement it (implements) ⚠️
Can intersect another one of its kind ⚠️
Can create a union with another one of its kind 🚫
Can be used to create mapped types 🚫
Can be mapped over with mapped types
Expands in error messages and logs 🚫
Can be augmented 🚫
Can be recursive ⚠️

⚠️ In some cases

Classes & OOP

Class members

Class Heritage

More features

Generics

The identity function → return back whatever is passed in

Without generics

function identity(arg: number): number {
  return arg;
}

Why not use the any type

function identity(arg: any): any {
  return arg;
}

Solution: use a type variable instead

function identity<Type>(arg: Type): Type {
  return arg;
}

and now

let out1 = identity<string>('hello')
let out2 = identity(42)
let out3 = identity<MyCustomType>(value)

Much more features

Resources

Thank you