我正在尝试在Typescript中定义'Definition'类型。定义可以是类构造函数也可以是对象 - 以后我会这样做:
if (this._isConstructor(definition)) {
return new definition(...args); // is a class - instantiate it
}
return definition; // is just an object - return it
我将我的类型定义为:
type Definition = {
new (arg?: object): object | object
}
似乎有用。但是,它看起来很难看,我想把它分成:
type Definition = {
Cstruct | object
}
type Cstruct = new (arg?: object): object
然而那就是呻吟
不能对类型缺少调用的表达式使用'new' 构建签名
尝试'新'时。
答案 0 :(得分:2)
使用type guard的解决方案:
type Definition = Cstruct | object
type Cstruct = {new (arg?: object): object}
function isConstructor(def: Definition): def is Cstruct {
// Here implement your test and return true or false
return true
}
function getObject(def: Definition, args = []) {
if (isConstructor(def))
return new definition(...args);
return def;
}