TypeScript:在类上调用时,typeof如何工作?

时间:2018-02-21 19:05:05

标签: typescript typeof

据我所知,TypeScript" typeof" operator执行类型查询,并允许您确保两个对象的类型相同,即使该类型未命名。但是,我在生产中发现了一些类似的代码:

function println (x) {
  document.write(x + '<br\>');
}

class SettingsBase {
  public static setting1: string;
  public static setting2: string;
}

class SettingsUser {
  private _settings: typeof SettingsBase;

  constructor(settings: typeof SettingsBase) {
    this._settings = settings;
  }

  public doStuff() {
    println(this._settings["setting1"]);
  }
}

class MySettings extends SettingsBase {
  public static setting1 = "foo";
  public static setting2 = "bar";
}

var baz = new SettingsUser(MySettings);
baz.doStuff();

SettingsUser中,构造函数采用类型为typeof SettingsBase的参数。 &#34; typeof&#34;是什么意思?一类?我不认为这应该有用,我可能会重构它,但我想知道它一开始是如何工作的。

1 个答案:

答案 0 :(得分:3)

类名前面的typeof关键字将提取类构造函数的类型,而不是仅代表实例的类型Foo。例如:

class Foo {}

var x: typeof Foo = Foo; // This is okay
var y: Foo = new Foo(); // Also okay