Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65835542/typescript-using-this-type-in-generic-mixin-when-declaration-true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...