Reputation: 45
I want to set a method in the parent class, the return value of which would be determined depending on the type of the value
field.
class A {
protected value: string;
public getValue(): this['value'] { .... }
}
class B extends A {
protected value: number;
}
new B().getValue() - should be a number
How can I do this? I tried to do it as shown above, but it doesn't work
Upvotes: 0
Views: 48
Reputation: 71
You can use generic classes/ functions from typescript to solve this.
class A<T> { value: T; getValue(): T }
You can read about it here: https://www.typescriptlang.org/docs/handbook/generics.html
Upvotes: 1