1 of 20

Typescript

What is it? Best practices, tips...

Thomas Winckell

Guillaume Monnet

@255kb

2 of 20

What is Typescript?

  • JS superset: JS program will be valid in TS
  • Statically typed (evaluated at compilation) vs JS dynamically typed
  • Transpiler: will transpile to JS

Any overhead?

No it’s only during development. After transpiling types disappear.

3 of 20

Usage / Configuration

Install TypeScript dependency npm install -D typescript

Compile .ts files with tsc command

tsc generates one .d.ts file (definition) and one .js file per ts file

Configure TypeScript compiler with tsconfig.json file

Can be generated using tsc --init

4 of 20

Where to install the compiler

  • best practice: install as a project dependency to avoid discrepancies betweens developers

  • use the tsc command via npm scripts, so it will use the local tsc bin (not the global one, if you installed it using -g)

5 of 20

IDE

Webstorm:

  • TypeScript path is configurable
  • by default, it takes TypeScript from the current project node modules

VSCode:

  • includes a recent Typescript version
  • switch VSCode to project version (bottom right corner)

6 of 20

TSlint

Typescript linter.

Install with npm install -D tslint and run tslint --init get default tslint.json config file.

Will start by extending ”tslint:recommended” set of rules, you can add any rule in ”rules” array as long as rules are “imported” in the rulesDirectory array.

Popular rules libs: Codelyzer (Angular), SonarTS (Sonarqube)

7 of 20

Usage with Babel / Webpack

  • TypeScript wants a little impact on runtime (as less polyfill as possible)
  • In order to use ES6 structures, you should set the target to ES6 or more
  • if you want to support old browsers, you need Babel or core-js
  • TypeScript is working well with webpack (see ts-loader)
  • Angular CLI is using Webpack and core-js for polyfilling (polyfill.ts)

8 of 20

Basic types

Primitives, enums, arrays, any...

9 of 20

Environment

  • Environment definition (node, browser)
  • EcmaScript definition (5, 6, 2015, 2016, 2017, 2018, next)

  • See node_modules/typescript/lib
  • Needs to install @types/node for node type definition files

10 of 20

Library types

  • If a library comes with types, you have nothing to do

  • Otherwise, try to install the library @types/LIBRARY_NAME

  • If a library has no type and you are in strict mode, you have to use require instead of import (everything you require will be typed as any)

11 of 20

Classes

Modifiers, constructor...

12 of 20

Type composition

Operators, interface, type...

13 of 20

Type assertion (cast)

14 of 20

Type inference

15 of 20

Index signatures and mapped types

16 of 20

Generics

17 of 20

Built-in types

Partial, Pick...

18 of 20

Decorators

/!\ Experimental

19 of 20

Reflect metadata

/!\ Experimental

20 of 20

Links / sources