简体   繁体   中英

TypeScript: extend "this" based on constructor parameters

I'm trying to add types to a class which extends "this" in the constructor.
I saw this question Typescript: extending "this" inside class but I don't know in advance which object would passed to the constructor.

class Baz<T extends object> {
    public test;
    constructor(props: T) {
        Object.assign(this, props);
    }
}

interface IFoo {
  foo: number;
}

const p = new Baz<IFoo>({foo: 1});
p.test;
p.foo; // Not recognized.

I'm trying to recognize as properties the fields passed as object.

I don't think you can do this with a constructor and a generic class. You could use a generic type parameter on the class to affect the type of a data member or a method's argument or return type, but not to add features to the class itself.

You can do it with a static method, though (or just a standalone function):

class Baz {
    public test: string = "something";

    private constructor() { // If you want it to be private; that's up to you
    }

    static create<T extends object>(props: T): Baz & T {
        const b = new Baz();
        Object.assign(b, props);
        return b as Baz & T;
    }
}

interface IFoo {
    foo: number;
}

const p = Baz.create<IFoo>({ foo: 1 });
p.test;
p.foo; // <== Works fine

Playground example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM