deepkit / deepkit-framework

A new full-featured and high-performance TypeScript framework
https://deepkit.io/
MIT License
3.14k stars 116 forks source link

Receive type support for class generics #209

Open marcus-sa opened 2 years ago

marcus-sa commented 2 years ago

I have a use case where it'd be better DX to be able to resolve a receive type from a class generic using it's constructor. Example:

class A<T> {
  constructor(type?: ReceiveType<T>) {
    const receivedType = resolveReceiveType(type);
  }
}

interface C {
  id: string;
}

class B extends A<C> {}
marcj commented 1 year ago

This is implemented here https://github.com/deepkit/deepkit-framework/commit/866009937768d680132555ee1574a9cb19fe5bbb.

It does not support expressions like class B extends A<C> {} because that would mean we have to put a constructor into B that defines C in its super class. I'm afraid of the performance implication of that so not sure if we should implement it. You could forward it manually though via

class B extends A<C> {
    constructor() {
        super(typeOf<C>());
   }
}
franjom commented 1 year ago

How about this use case:

class A {
    constructor() {
    }
}

class B<T> extends A {
    constructor(type?: ReceiveType<T>) {
        super();
        const t = resolveReceiveType(type);
    }
}

class C {
}

const b = new B<C>();

I am getting the following error:

Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
    at new B (app.ts:35:5)
    at ./src/app.ts (app.ts:44:11)
    at __webpack_require__ (bootstrap:24:1)
    at startup:6:1
    at startup:6:1