0

Is there a way to tell TypeScript that a static method returns an object that called the method?

I have this base class:

export default class model {
  public static create() {
    let t = new this() as this
    // set extra information here
    return t
  }
}

I then extend the class like this:

export default class purchases extends model { /* extra methods */ }

I then call it like this:

let p = purchases.create({ my: 'options' })

TypeScript then tells me that p is of type model when actually it should be of type purchases.

When I cast t to this or say public static create(): this I get this error:

A 'this' type is available only in a non-static member of a class or interface.

What can I do to say that "This static method returns an instance of the object that called it"?

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

0

The easiest way might just be to downcast the instance

class model {
  public static create() {
    let t = new this();
    // set extra information here
    return t;
  }
}

class purchases extends model { /* extra methods */ }

let p = purchases.create() as purchases; // downcast
tarling
  • 1,887
  • 2
  • 19
  • 27
  • That is the "workaround" that I decided to go with. I hope they implement something that is described within the link above. – Get Off My Lawn Dec 11 '17 at 22:18
  • 1
    Note that this is a downcast, not an upcast - see e.g. https://stackoverflow.com/questions/23414090/what-is-the-difference-between-up-casting-and-down-casting-with-respect-to-class – Oliver Charlesworth Dec 11 '17 at 23:17