typescript中函数即是构造函数又是普通函数的函数怎么写?

interface A {
 (el?: HTMLElement, options?: Options): any;
 new(el?: HTMLElement, options?: Options): any;
}

const F:A = function(){

}

函数F会报错:

不能将类型“() => void”分配给类型“A”。
类型“() => void”提供的内容与签名“new (el?: HTMLElement | undefined, options?: Options | undefined): any”不匹配。ts(2322)

阅读 3.3k
1 个回答
type Options = {}

interface AConstructor {

(el?: HTMLElement,options?: Options): void,

new (el?: HTMLElement,options?: Options): void

}

const A = function (this: AConstructor | void, ...args) {

if (!(this instanceof A)) {

return new A(...args)

}

return ''

} as AConstructor

const B = A(document.body, {});

const C = new A(document.body, {});

编译成

"use strict";
const A = function (...args) {
 if (!(this instanceof A)) {
 return new A(...args);
 }
 return '';
};
const B = A(document.body, {});
const C = new A(document.body, {}); 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题