简体   繁体   English

无法在 Typescript 中定义类类型

[英]Unable to define class type in Typescript

I'm attempting to define a 'Definition' type in Typescript.我试图在 Typescript 中定义一个“定义”类型。 A Definition can be either a class constructor or an object - such that later I do:定义可以是类构造函数或对象 - 稍后我会这样做:

 if (this._isConstructor(definition)) {
  return new definition(...args); // is a class - instantiate it
 }

return definition; // is just an object - return it

I have my type defined as:我的类型定义为:

type Definition = {
  new (arg?: object): object | object
}

which seems to work.这似乎有效。 However, it looks ugly and I want to split it out into:但是,它看起来很丑,我想将其拆分为:

type Definition = {
 Cstruct | object
}

type Cstruct = new (arg?: object): object

however that then moans that然而那然后呻吟着

Cannot use 'new' with an expression whose type lacks a call or construct signature不能对类型缺少调用或构造签名的表达式使用“new”

when trying to 'new' it.当试图“新”它时。

A solution using a 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;
}

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

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