【问题标题】:Typescript constructor interfaces [closed]Typescript构造函数接口[关闭]
【发布时间】:2020-11-17 14:42:21
【问题描述】:

这个例子来自docs

interface ClockConstructor {
  new (hour: number, minute: number): ClockInterface;
}

interface ClockInterface {
  tick(): void;
}

function createClock(
  ctor: ClockConstructor,
  hour: number,
  minute: number
): ClockInterface {
  return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("beep beep");
  }
}

class AnalogClock implements ClockInterface {
  constructor(h: number, m: number) {}
  tick() {
    console.log("tick tock");
  }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

正如文档所说:

因为 createClock 的第一个参数是 ClockConstructor 类型,所以在 createClock(AnalogClock, 7, 32) 中,它会检查 AnalogClock 的构造函数签名是否正确。

我想知道没有构造函数没有任何限制,所以如果我像下面这样更改AnalogClock 类,Typescript 不会给我任何错误。

class AnalogClock implements ClockInterface {
    // constructor(h: number, m: number) {}  <-- this like commented out.
    tick() {
      console.log("tick tock");
    }
  }

【问题讨论】:

标签: typescript interface


【解决方案1】:

如果你没有明确指定构造函数,将使用默认构造函数according to MDN Docs

class AnalogClock implements ClockInterface {
  tick() {
    console.log("tick tock");
  }
}

// is equal to
class AnalogClock implements ClockInterface {
  constructor() {}

  tick() {
    console.log("tick tock");
  }
}

如果你没有在子类上指定构造函数,构造函数也会继承super(...args)调用

class Ancestor {
  foo: string;
  
  constructor(foo: string) {
    this.foo = foo;
  }
}

class Child extends Ancestor {
  constructor(foo: string) {
    super(foo);
  }
}

// equals to
class Child extends Ancestor {}

playground link

【讨论】:

  • 默认构造函数的架构是否与定义的架构ClockConstructor匹配?
  • 是的,确实如此。添加了游乐场链接,对上述答案有更好的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多