Typescript

up:: JavaScript

Ressources

Why Typescript

  • Type checking
  • Code completion
  • Additional features

When to use TS

  • Just use enough Types to be helpful
    • Think about types more as documentation rather than โ€œtypescript all the thingsโ€
  • What is good about Typescript is that it adds auto-completion

Types

Function

Type alias

type Employee = {
	readonly id: number,
	name: string,
}

Namespaces

global.d.ts is a global namespace

Defining type

Interfaces

Interfaces are basically type definitions for objects.

interface Restaurant {
	name: string;
	rating: string;
	diet: dietOptions;
}

In order to make an interface โ€˜loop-ableโ€™, we need to specify the key:

interface Tag {
    [key: string]: string | undefined; // return value from the key is either a `string` (since all values are strings), or `undefined` (since some keys are optional)
    tag: string;
    icon: string;
    from?: string;
    to?: string;
    fromDark?: string;
    toDark?: string;
  }

Type

Defining a type looks a bit like defining a variable with let. By convention, they are UpperCamelCased.

type MyStringType = string;
let s: MyStringType = 'hello';

Prefer interfaces

According to the documentation, it is best practice to prefer using interfaces and only use type when specific features are required.

type dietOptions = "Vegetarian" | "Vegan" | "Pescetarian"

Type Erasure

The types are only checked while compiling and then โ€˜thrown awayโ€™. Typescript checks all the type-specific syntax and then compiles into pure JavaScript.

Letโ€™s take a line like this:

type MyNumberType = number;

All the Typescript syntax gets evaluated and then erased. That leaves zero JavaScript to be compiled. When running the program, it returns undefined.

Summary

JavaScript: syntax check โ†’ execution. TypeScript: syntax check โ†’ type check โ†’ execution.

Get the return type of a function

This is handy when initialising a variable.

let wrapper: ReturnType<typeof mount>;