今天看TypeScript Deep Dive的时候有个例子
interface Crazy {
new(): {
hello: number;
};
}
class CrazyClass implements Crazy {
constructor() {
return { hello: 123 };
}
}
// Because
const crazy = new CrazyClass(); // crazy would be { hello:123 }
编译的时候会报错 Type ‘CrazyClass’ provides no match for the signature ‘new (): { hello: number; }’
这里因为当一个类实现了一个接口时,只对其实例部分进行类型检查。 constructor存在于类的静态部分,所以不在检查的范围内。下面对构造函数进行类型检查。
// 构造方法使用
interface Crazy {
new(): {
hello: number;
};
}
// 类使用
interface CrazyClassInterface {
hello: number;
}
class CrazyClass implements CrazyClassInterface {
hello: number;
constructor() {
this.hello = 123;
}
}
function ct1(ct: Crazy) {
return new ct();
}
let obj = ct1(CrazyClass);
console.log(obj);
修改为以上代码,Crazy接口修改为构造函数使用,类实现CrazyClassInterface接口也存在构造函数约束。