CWright
CWright

Reputation: 2098

Unable to define class type in Typescript

I'm attempting to define a 'Definition' type in 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

when trying to 'new' it.

Upvotes: 2

Views: 152

Answers (1)

Paleo
Paleo

Reputation: 23772

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

Upvotes: 2

Related Questions