Contents

TypeScript Notes

安装与执行

yarn add typescript
yarn global add ts-node

yarn add @types/{MODULE}
yarn add {MODULE}

ts-node ./src/index.ts

Cannot find name ‘console’ ? => yarn add @types/node

范型

class MyClass {}
interface Example {
  a: string;
  b: number;
  c: MyClass;
  d: () => void;
  e: new () => MyClass;
}

type NonConstructorKeys<T> = { [P in keyof T]: T[P] extends new () => any ? never : P }[keyof T];

// NonConstructorKeys<Example> 的类型是 'a' | 'b' | 'c' | 'd'
var e: Example = {
  a: 'xxx',
  b: 666,
  c: new MyClass(),
  d: () => {
    console.log('function');
  },
  e: MyClass,
};

type ArrayToUnion<T extends any[]> = T[number];

装饰器

类装饰器

function ClassDecorator(target: new () => {}, metadata: object) {
  console.log(new target());
  console.log(metadata);
}

@ClassDecorator
class MyClass {}

类属性装饰器

function PropertyDecorator(target: undefined, metadata: object) {
  console.log(target);
  console.log(metadata);
}

class MyClass {
  @PropertyDecorator
  name!: string;
}

类方法装饰器

function MethodDecorator(target: (arg1: string, arg2: number) => void, metadata: object) {
  console.log(target('hello', 42));
  console.log(metadata);
}

class MyClass {
  @MethodDecorator
  myMethod(arg1: string, arg2: number) {
    console.log(`method args: ${arg1}, ${arg2}`);
  }
}

函数重载

type GreetFunction = {
  (name: string): string;
  (age: number): string;
};

const greet: GreetFunction = (nameOrAge: string | number): string => {
  if (typeof value === 'string') {
    return `Hello, ${value}`;
  }
  return `You are ${value} years old.`;
};

function greet(name: string): string;
function greet(age: number): string;
function greet(nameOrAge: string | number): string {
  if (typeof nameOrAge === 'string') {
    return `Hello, ${nameOrAge}!`;
  }
  return `You are ${nameOrAge} years old.`;
}