Chet
Chet

Reputation: 19889

Partially applying class constructor in Typescript

I was reading this answer about partially applying class constructors in JavaScript and tried to so something similar in Typescript.

First thin I notices is that .bind is untyped. So I tried to create my own type signature:

class Container<State> {
    constructor(public initialState: State) {}

    static of<State>(state: State): typeof Container<State> {
        return Container.bind(null, state)
    }
}

The compiler doesn't seem to like typeof Container<State>. Any ideas how I can get this to work?

I could use a factory function, but I need to be able to use the new keyword on this for it to work with the existing setup I have that expects a class with no constructor arguments...

Upvotes: 1

Views: 453

Answers (1)

jcalz
jcalz

Reputation: 330436

You want of to return a no-arg Container<State> constructor. TypeScript allows you to denote a constructor type as the presence of a new function which returns an object.

type ContainerConstructor<State> = {
  new(): Container<State>;
}

class Container<State> {
  constructor(public initialState: State) { }

  static of<State>(state: State): ContainerConstructor<State> {
    return Container.bind(null, state)
  }
}

const ctor = Container.of('hello');
const container: Container<string> = new ctor();

Hope that helps.

Upvotes: 2

Related Questions