DEV Community

Cover image for TypeScript syntax summary
André Hatlo-Johansen
André Hatlo-Johansen

Posted on

TypeScript syntax summary

I use this blog to store information I may need to refresh up on at a later date.

Reference to FlavioCopes blog, a great place to learn.

TypeScript is one of the fastest rising technologies of 2018. This brief summary is filled with what you need to know to understand its key concepts.


TypeScript is built by Microsoft. Its open source, developed public at https://github.com/Microsoft/TypeScript.

A superset of ECMAScript 2015, also know as ES6, which means that any valid JS is also valid TypeScript.

Run npm install -g typescript to globally install the TypeScript compiler on your system, available to you using the tsc command.

Create an app.ts file.

Write your first program:

const greet = () => {
  console.log('Hello world!')
}
greet()
Enter fullscreen mode Exit fullscreen mode

As you see, its just plain JavaScript, but stored in a .ts file.

Compile the program using the tsc app.ts command.

The compiler compiles the program into a new file: app.js, with this content:

var greet = function () {
  console.log('Hello world!')
};
greet();
Enter fullscreen mode Exit fullscreen mode

Just like old JavaScript, the TS compiler compiles TypeScript to ES5 by default, which means that its almost guaranteed to be suppored by all modern browsers.

To change the compilation target to another version, for example to ES2018 run the following:

`tsc app.ts --target ES2018`:
Enter fullscreen mode Exit fullscreen mode
const greet = () => {
  console.log('Hello world!');
};
greet();
Enter fullscreen mode Exit fullscreen mode

Here almost nothing changed except for the additional semicolons.

Play around with TS to JS compilation, check out https://www.typescriptlang.org/play/.

TYPING


Most important functionality provided by TypeScript is the type system:

  • static types
  • interfaces
  • type interence
  • enums
  • hybrid types
  • generics
  • union/intersection types
  • access modifiers
  • null checking

It resembles languages like Go or C, so if you've coded these languages you already know how this works. Unike dynamic languages like Python or Ruby, this is all new.

The type system allows adding types to:

  • variables
  • function arguments
  • function return types

Giving a more rigid structure to your programs.

This is how:

You define a string variable in TypeScript:

const greeting : string = "hello!"
Enter fullscreen mode Exit fullscreen mode

A function accepts an argument of a specific type:

const multiply = (a: number, b: number) => {
  return a * b
}
Enter fullscreen mode Exit fullscreen mode

You declare their return value:

const multiply = (a: number, b: number): number => {
  return a * b
}
Enter fullscreen mode Exit fullscreen mode

Valid types are:

  • number
  • string
  • boolean
  • enum
  • void
  • null
  • undefined
  • any
  • never
  • Array
  • tuple

any is a type that identifies, as its name says, any type.

CLASSES


Like JavsScript, you declare classes like this:

class Car {

}
Enter fullscreen mode Exit fullscreen mode

Defining class fields:

class Car {
  color: string
}
Enter fullscreen mode Exit fullscreen mode

Fields are public by default. You can set a field to be private or protected:

class Car {
  public color: string
  private name: string
  protected brand: string
}
Enter fullscreen mode Exit fullscreen mode

Private fields can only be accessed by the class that its declared in.

Protected fields can only be accessed by deriving classes.

TypeScript also has static fields, which are class fields instead of object fields:

class Car {
  static numberOfWheels = 4
}
Enter fullscreen mode Exit fullscreen mode

initialize fields with a constructor:

class Car {
  color: string

  constructor(theColor: string){
    this.color = theColor
  }

}
Enter fullscreen mode Exit fullscreen mode

Shorthand syntax to make it simpler:

class Car {
  constructor(public color: string){}

  printColor() {
    alert(this.color)
  }
}

(new Car('red')).printColor()
Enter fullscreen mode Exit fullscreen mode

A field can be read only:

class Car {
  readonly color: string
}
Enter fullscreen mode Exit fullscreen mode

in this case its value can only be set in the constructor.

Class methods:

class Car {
  color: string
  constructor(public color: string) {
    this.color = color
  }
  drive() {
    console.log('You are driving the car')
  }
}
Enter fullscreen mode Exit fullscreen mode

You create objects from those classes, like in JavaScript, using the new keyword:

const myCar = new Car('red')
Enter fullscreen mode Exit fullscreen mode

You can extend an existing class using the extend keyword:

class ElectricCar extends Car {
  //..
}
Enter fullscreen mode Exit fullscreen mode

Call super() in the constructor and in methods to call the extended class corresponding method.

ACCESSORS


Getters and setters:

class Car {
  private _color: string

  get color(): string {
    return this._color
  }

  set color(color: string) {
    this._color = color
  }
}
Enter fullscreen mode Exit fullscreen mode

ABSTACT CLASSES


To define an abstract class there needs to be a class that extends it, and implements its eventual abstact methods:

abstact class Car {
  abstract drive()
}

class SportsCar extends Car {
  drive() {
    console.log('You are driving a sports car')
  }
}
Enter fullscreen mode Exit fullscreen mode

INTERFACES


Interfaces build upon basic types. Use an interface as a type, and its interface can contain other type definitions:

interface SetOfNumbers {
  a: number;
  b: number;
}

const multiply = (set: SetOfNumbers) => {
  return set.a * set.b
}

multiply({ a: 1, b: 2 })
Enter fullscreen mode Exit fullscreen mode

An interface can also be an interface for a class implementation:

interface Car {
  name: 'string'
  new (brand: string)
  drive(): void
}

class SportsCar implements Car {
  public name

  constructor(public brand: string) {
    //..
  }

  drive() {
    console.log('You are driving a sports car')
  }
}
Enter fullscreen mode Exit fullscreen mode

FUNCTION FEATURES


Functions can have optional parameters using the ? symbol after the parameter name:

class Car {
  drive(kilometers?: number) {
    if(kilometers) {
      console.log('Drive the car for ${kilometers} kilometers')
    } else {
      console.log('Drive the car')
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Parameters can have default values:

class Car {
  drive(kilometers = 10) {
    console.log('Drive the car for ${kilometers} kilometers')
  }
}
Enter fullscreen mode Exit fullscreen mode

Functions can accept a verying number of parameters by using rest parameters:

class Car {
  drive(kilometers = 10, ...occupants: string[]) {
    console.log('Drive the car for ${kilometers} kilometers, with those people on it:')
    occupants.map((person) => console.log(person))
  }
}
(new Car()).drive(20, 'Andre', 'Peter', 'Roger')
Enter fullscreen mode Exit fullscreen mode

ENUMS


A great way to defined named constants.

enum Order {
  First,
  Second,
  Third,
  Fourth
}
Enter fullscreen mode Exit fullscreen mode

Simply reference Order.First, Order.Second etc.

You can assign values to constants explicitly:

enum Order {
  First   = 0,
  Second  = 1,
  Third   = 2,
  Fourth  = 3
}
Enter fullscreen mode Exit fullscreen mode

or use strings:

enum Order {
  First = 'FIRST' ,
  Second = 'SECOND',
  Third = 'THIRD',
  Fourth = 'FOURTH'
}
Enter fullscreen mode Exit fullscreen mode

GENERICS


A new feature not available in many programming languages. You can create a function, interface or class that works with different types, without specifying the type up front.

It is mutable, so if you change the type at compile time, the compiler will throw an error.

We could do this by omitting types to all or using any.

But with generics all the tooling is going to be able to help us.

Example:

function greet<T>(a: T) {
  console.log('Hi ${a.name}')
}
greet({name: 'André'})
Enter fullscreen mode Exit fullscreen mode

The T symbol identifies a generic type.

the type can be resistricted to a certain class family or interface, using the extends keyword:

interface Greetable { name: string }
function greet<T extends Greetable>(a: T) {
  alert('Hi ${a.name}!')
}
greet({ name: 'André'})
Enter fullscreen mode Exit fullscreen mode

WANT MORE?

We just went over the basics of TypeScript, go to the official docs for more!

Top comments (0)