为什么可以创建这样的类型?
因为javascript
。例如Date
目的。
TS 允许创建ConstructOrCall
类型,因为向后兼容性。
假设您有一些遗留代码:
export const PointCreator = function (x,y) {
if (new.target) {
// If this function was called with new keyword
this.x = x
this.y = y
} else {
// if function was called as a regular function
return 42
}
}
// static test method
PointCreator.test = function (a) {
}
const x = new PointCreator(1, 2)
并且您想为其编写打字。那么这个类型就可以了
declare module 'legacy' {
export type PointCreator = {
new(x: number, y: number): { x: number, y: number },
test(test: number): number,
(foo: number): number,
}
}
但是,您无法在纯打字稿中创造这样的价值。
另外,我不明白为什么函数 test() 需要是静态的
因为PointCreator
是一个构造函数类型并且test
直接定义为构造函数属性的方法。为了将其用作实例方法,您应该更新您的类型:
type PointCreator = {
new(x: number, y: number): { x: number, y: number, test: (arg: number) => number },
}
const PointCreation: PointCreator = class {
constructor(public x: number, public y: number) { }
test = (arg: number) => 42 // ok
}