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.
CodePudding user response:
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