TypeScript: Using "this" type in Generic Mixin when declaration=true?

When I use the following code in an index.ts-file, everything works fine:

class A<T> {
  constructor(public t1: T) {}
}
class B<T> extends A<T> {
  t2!: T;
}

function mixinC<TConstructor extends new (...args: any[]) => A<unknown>>(Base: TConstructor) { // Note "unknown"
  return class extends Base {
    t3!: this['t1'];
  }
}

export class C<T> extends mixinC(B)<T> {
  t4!: T;
}

const c = new C('somestring');
c.t1; // string OK
c.t2; // string OK
c.t3; // string OK !!
c.t4; // string OK

Here, I used the this type (this['t1']) trick to dynamically tell TS which type the (unknown) generic T has. VS Code regonizes all types correctly.

But then I try to compile the code with declaration=true option, which gives me the following .d.ts file:

declare class A<T> {
    t1: T;
    constructor(t1: T);
}
declare class B<T> extends A<T> {
    t2: T;
}
declare function mixinC<TConstructor extends new (...args: any[]) => A<unknown>>(Base: TConstructor): {
    new (...args: any[]): {
        t3: unknown;
        t1: unknown;
    };
} & TConstructor;
export declare const C_base: {
    new (...args: any[]): {
        t3: unknown;
        t1: unknown;
    };
} & typeof B;
declare class C<T> extends C_base<T> {
    t4: T;
}
declare const c: C<string>;

As you can see, for the case of t3, the type information is lost. Consequentially, if I import the built index.js from another ts-file (in same directory) and try again

import {C} from './index';
const c = new C('somestring');
c.t3; // unknown!

I cannot recover it (while t1, t2, t4 still work).

I also tried changing manually unknown to this['t1'] in the .d.ts-file again, but that logically gives me the error that this type is only available in classes.

Is there anything that can be done about it?



Read more here: https://stackoverflow.com/questions/65835542/typescript-using-this-type-in-generic-mixin-when-declaration-true

Content Attribution

This content was originally published by Remirror at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: