获取变量类型 -- Typescript类型编程篇(1)

7,055 阅读1分钟

typeof

对于已经存在的变量,可以通过typeof获取其类型(注意和js中typeof做区分):

const obj = {
  name: "name",
  age: 12,
};

type Person = typeof obj;

// 等价于
type Person = {
  name: string;
  age: number;
};

获取函数类型:

function foo(name: string): void {}
type Foo = typeof foo;

// 等价于
type Foo = (name: string) => void

获取类的构造器和静态成员类型:

class Person {
  name = "st";
  age = 12;
  static lifetime = 100;
  static staticMethod() {}
  method() {}
}

type PersonConstructor = typeof Person;

// 等价于
type PersonConstructor = {
  new (): Person;
  lifetime: number;
  staticMethod(): void;
};