关于typescript类型检查

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

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);

这里的

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

这几行谁能帮我解答么 ??
原文地址:https://typescript.bootcss.co...

阅读 2.1k
2 个回答

没有任何的特殊之处。Interface 可以定义所有对象类型的接口,这只是其中一种。

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

这个接口的意思就是:实现了一个类接口,可以检查 new 关键字的调用方法类型。 同时如果是一个函数,则只能用 new 关键字调用,不能直接调用。

【同样的还有其他的定义】:

定义函数接口,实现了 callable,但是不能用 new 关键字。

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

实现了类接口。但是不会检查 constructor ,因为这属于类静态部分。

interface ClockConstructor {
    constructor(hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick(); // 定义接口 ClockInterface 这个接口需要实现tick函数
}

// createClock 函数返回 ClockInterface 接口
// 也就是说 new ctor(hour, minute) 这个表达式的结果必须是实现了 ClockInterface接口的对象, 这里是 new ctor 因此要求 ctor参数对应的对象必须实现tick函数
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进