Typescript 查缺补漏

时间:2022-05-06
本文章向大家介绍Typescript 查缺补漏,主要内容包括Types、Classes、Object Literals、Generics、Iterators & Generators、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Types

Casting:

let input = xxx as HTMLInputElement;
let input = <HTMLElement>xxxx;

Object Shapes:

Typescript only cares about the shape of an object.

Interfaces:

  • only describe structure, no implementation
  • don't compile to any js code
  • DRY, easy refactoring
  • open, can be extended later on. (extends)

any:

never:

Nothing can be assigned to never.

function return type void.

Classes

still protofypal inheritance, but better syntax.

static method:

static createPerson() {
}

instance / public fields:

class Person {
    static population = 122; // public (static) field
    country = 'China'; // instance field

    constructor(name) {
    }
}

inheritance:

class Person : Human {
    constructor() {
        super();
    }
}

super.xxx(); // function invoke.

Species:

    static get [Symbol.species]() {
        return Array;
    }

Mixins:

Enums:

enum Gender {
    Male,
    Female
}

Arrays:

Tuples:

Fixed length.

let t2: [string, number];
t2 = ['angular', 1];

Type Aliases:

interface sometimes is not good enough.

type keyword to define a type alias:

type Color = [number, number, number];
let red: Color = [255, 0, 0];

can be exported.

Object Literals

Enhanced:

let person = {
    __proto__ : String.prototype,
    name: 'Dave',
    company,
    [`${company}Title`]: 'CTO',
    toString() {
        return `${super.toString()}xxx`;
    }
};

Destructured Assignment:

Rest, Spread Properties:

...

rest: and the rest goes here

spread: and all the properties on this object.

Getters, Setters:

Function - Types:

Functions have a type just like any other value.

interface can also describe functions:

interface ClickListener {
    (this: Window, e: MouseEvent): void
}

const myListender: ClickListener = (e) => {
    console.log(e);
};

this, calling context must be window.

Function - Parameters:

named, optional, default value, rest parameters(...).

Generics

let persons = Array<[String, String]>(20);

can specify constraints on generic types:

function calc<T extends number>(x: T, y: T) {

}

can also be use with interface:

interface IFileReader<T extends File> {
    read(file: T): Blod
}

Access Modifier Keywords:

public, protected, private

Function overloading:

Allows us to have more than one function "head", but a single implementation.

function add(x: number, y: number): number; // this pattern ok
function add(x: string, y: string, radix: number): number; // this pattern ok

function add(x: number | string, y: number | string, radix: number = 10): number { // must match 2 patterns above.
    return parseInt(`${x}`, radix) + parseInt(`${y}`, radix);
}
add(1, '4'); // not ok

Iterators & Generators

Iterators: keeping track of current position, next()

Iterables

  • support for .. of loop.
  • Requires implementation of Symbol.iteractor method
  • Array, Map already support it.

Generators:

  • yield
  • function*() syntax
  • returns an iterator
  • State of closure is preserved between .next() calls.
  • Execution Can be Paused (yield).

it.next() goes in the loop, and pause after yield until next it.next() call.

Iterators:

The ability to pass values in while iterating.

console.log(it.next(134).value);

yield* keyword.

yield* [1, 2, 3];