Hello I am trying to auto-type a class property based on the constructor's entry parameters. Ive tried something like the following:
type TypeA = { a: string };
type TypeB = { b: boolean };
type TypeC = { c: number };
class MyClass<T extends TypeA | TypeB | TypeC> {
prop: T;
foo?: string;
bar?: number;
constructor (prop: TypeA, param2?: number)
constructor (prop: TypeB, param2?: string)
constructor (prop: TypeC)
constructor(prop: T, param2?: number | string) {
this.prop = prop;
if (typeof param2 === 'number') {
this.bar = param2;
} else if (typeof param2 === 'string') {
this.foo = param2;
}
}
}
declare const prop: TypeB;
const instance = new MyClass(prop, 'test');
instance.prop; // should be TypeB!
In this case, the property is being types as the union of types, even though I passed a prop of a specific type in the union. Is there a way to achieve having the property typed depending on the constructor parameter type?
