Skip to content

Typescript

wangb edited this page Nov 1, 2018 · 10 revisions

A list of tricks on Typescript and it's type system

Setup a Typescript Project

npm init
npm i -D typescript webpack webpack-cli source-map-loader awesome-typescript-loader ts-loader tslint tslint-loader ts-node
npx tsc --init

This is my routine for create a ts project. I use webpack and awesome-typescript-loader to transpile and bundle the ts code into es code. The tslint and is used for lint my ts code. The ts-node is used as a repl envrionment and run ts files directly.

Here is a simple webpack.config.js for ts:

const path = require('path')
const { CheckerPlugin } = require('awesome-typescript-loader')

module.exports = {
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'app.bundle.js'
  },
  resolve: {
    extensions: ['.js', 'json', '.jsx', '.ts', '.tsx']
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        enforce: 'pre',
        loader: 'tslint-loader'
      },
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  },
  plugins: [
    new CheckerPlugin()
  ]
}

I also use prettier to format my ts code.

Basic Types

Typescript have the same simple types as JavaScript those are number, string, bool, array []. And there are more types to express more data structure like:

  • tulpe: typed array with fixed number of elements
  • enum: enum Color = { Red, Green, Blue }, those values will converto numbers begin with 0, also we change the start number or manually set all the values. Values can be string too. Values can not only assign by constant value, but also expression. Enum are objects at runtime.
  • never: represents the type of values that never occur. For instance, never is the return type of a function that always throws an exception or one that never return. The never type is a subtype of, and assignable to, every type.
  • null, undefined: by default, those two types are subtypes of all other types. That means you can assign null and undefined to something like number

Interfaces

Typescript's type-checking focusse on the shape that value have.

  • optionsal properties
  • readonly properties
  • Object literals get special type checking. It will fail the type-checker if an literal object has any property that the target type doesn't have.
  • function types: interfaces can describe function type.
  • indexable types: interface can describe indexable types like map[T1, T2], array[T]. There are two types of supported index signatures: string and number. Javascript will automaticlly convert number index to a string, so if a interface both have string and number indexer, the type returnd by number indexer must be a subtype of the type returned by string indexer.
  • class types: When a class implements a interface Typescript only check the instace side (method, property) of the class, not static side (constructor, static property, static method).
  • extends

Classes

Typescript classes are like es6 classes.

  • abstract classes

modifier

  • public: default
  • private: unable be accessed from outside of its containing class
  • protect: like private but can be accessed within deriving classes.
  • readonly

Functions

  • this
  • overload: We have to supply multiple function types for the same function as a list of overloads and a function that have type like (a: any, b: any) => any.

Genertics

  • constraints: <T extends ConcreteT>
  • keyof: <T, K extends keyof T>
  • Class Types: create<T>(c: {new(): T; }): T

Type Compatibility

Type compatibility in TypeScript is based on structural subtyping. TypeScript’s structural type system was designed based on how JavaScript code is typically written. Because JavaScript widely uses anonymous objects like function expressions and object literals, it’s much more natural to represent the kinds of relationships found in JavaScript libraries with a structural type system instead of a nominal one.

Advanced Types

  • Intersection Types: A & B & C (structural intersection)
  • Union Types: A | B | C (structural union)
    • Type Guards: 1. type assertion, 2. return type is type predicate 3. typeof (primitive types) 4. instanceof
  • nullable: ! syntax
  • type aliases: type T = string
  • string/numeric literal types: type Easing = 'ease-in' | 'ease-out' | 'ease-in-out'
  • Discriminated Unions (tagged unions or algebraic data types): discriminant, union, type guards on the common property
  • this type
  • index types
  • mapped types