Skip to content

TypeScript Basics

类型标识

class 的 implements 针对 type 和 interface class 的 extends 针对 class

从类型创造类型

JavaScript 中 object 的键类型总会被转换为字符串

Generics

class GenericNumber<NumType> {
  zeroValue: NumType;
  add: (x: NumType, y: NumType) => NumType;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
  return x + y;
};

Keyof

type Point = { x: number; y: number };
type P = keyof Point;
// type P = "x" | "y"

type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number

Typeof

function f() {
  return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;

/*
type P = {
    x: number;
    y: number;
}
*/

Indexed

只能以 type 作为 index

type Person = { age: number; name: string; alive: boolean };
type I2 = Person[keyof Person];
// type I2 = string | number | boolean

Conditional

type NameOrId<T extends number | string> = T extends number
  ? IdLabel
  : NameLabel;

Mapped

基于其它类型的参数创造类型

type OnlyBoolsAndHorses = {
  [key: string]: boolean | Horse;
};

const conforms: OnlyBoolsAndHorses = {
  del: true,
  rodney: false,
};

遍历 keys 来创造类型

type OptionsFlags<Type> = {
  [Property in keyof Type]: boolean;
};

type FeatureFlags = {
  darkMode: () => void;
  newUserProfile: () => void;
};

type FeatureOptions = OptionsFlags<FeatureFlags>;

/*
type FeatureOptions = {
    darkMode: boolean;
    newUserProfile: boolean;
};
*/

Template Literal

type PropEventSource<Type> = {
  on(
    eventName: `${string & keyof Type}Changed`,
    callback: (newValue: any) => void
  ): void;
};

declare function makeWatchedObject<type>(
  obj: Type
): Type & PropEventSource<Type>;

const person = makeWatchedObject({
  firstName: "Saoirse",
  lastName: "Ronan",
  age: 26,
});

person.on("firstNameChanged", () => {});