interface Foo<T> {
getValue(): T;
}
class Foo1 implements Foo<string> {
__value: string;
constructor(value: string) {
this.__value = value;
}
getValue(): string {
return this.__value;
}
}
class Foo2 implements Foo<number> {
__value: number;
constructor(value: number) {
this.__value = value;
}
getValue(): number {
return this.__value;
}
}
class Bar<T extends Foo1 | Foo2> {
private __foo: T;
constructor(foo: T) {
this.__foo = foo;
}
getValueOfFoo() {
return this.__foo.getValue();
}
}
const bar1 = new Bar(new Foo1('hello'));
const val1: string = bar1.getValueOfFoo();
const bar2 = new Bar(new Foo2(12345));
const val2: number = bar2.getValueOfFoo();
I expected the return values of 42 and 45 line to be string and number but they aren't.
How can I define the type of method that can returns proper type depends on object type be provided thru constructor?