Answer the question
In order to leave comments, you need to log in
How do inheritance and generics go together?
I know what extends are and I know what generics are, but sometimes I see code in which they are used together and it's not clear. It looks something like this:
I don’t even know what words to google to understand what such a record means.
Please explain in general terms the meaning of such a record or advise what exactly to read. At least even in English.
class A extends B<string> {}
Answer the question
In order to leave comments, you need to log in
For example:
class Result<T>{
public readonly result;
constructor(result: T){
this.result = result;
}
}
class NumberResult extends Result<number>{
constructor(result: number){
super(result);
}
public ResultPlusOne(){
return this.result + 1;
}
}
Result<T>
is an open generic, that is, in the future, another\types or types must be specified in place of T in order to create instances of the class. let result = new Result<number>(42)
class Result{
public readonly result;
constructor(result: number){
this.result = result;
}
}
class NumberResult extends Result<number>
Classes in TypeScript can be generic, that is, they are parameterized with some type (or even several types). When inheriting, you need to pass such a parameter explicitly so that TypeScript knows what to substitute in place of the generic type.
class Base<T> {
protected val: T;
}
class A extends Base<string> {
methodA(): string {
return this.val; // Ok, так как здесь val имеет тип string
}
}
class B extends Base<number> {
methodB(): number {
return this.val; // тоже ok, так как здесь val имеет тип number
}
}
Usual javascript inheritance, what else to look for, he himself said that you know what extends is
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question