Z
Z
zlodiak2021-08-08 00:54:14
typescript
zlodiak, 2021-08-08 00:54:14

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

4 answer(s)
I
Ilya, 2021-08-08
@zlodiak

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.
If we want, for example, to put number in place of T and create an instance of the class,
let result = new Result<number>(42)
then the compiler will create a private generic for this, which will look something like this, but you will not see it anywhere:
class Result{
  public readonly result;
  constructor(result: number){
    this.result = result;
  }  
}

Record class NumberResult extends Result<number>
Means inheritance from such a class Result in which a specific type has already been substituted for T

D
Dmitry Belyaev, 2021-08-08
@bingo347

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
  }
}

V
Vitaly Stolyarov, 2021-08-08
@Ni55aN

generic in this case is no different as innew B<string>()

P
Pavel Shvedov, 2021-08-08
@mmmaaak

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 question

Ask a Question

731 491 924 answers to any question