繁体   English   中英

无法在 Typescript 中定义类类型

[英]Unable to define class type in Typescript

我试图在 Typescript 中定义一个“定义”类型。 定义可以是类构造函数或对象 - 稍后我会这样做:

 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”

当试图“新”它时。

使用类型保护的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM