Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a method to a prototype of a generic class in typescript

Tags:

typescript

I'm trying to add a method to a prototype of PromiseLike<T> With String it is not a problem:

declare global {
    interface String {
        handle(): void;
    }
}

String.prototype.handle = function() {
}

Compiles OK

But if I try to do the same with PromiseLike<T>, I get a compile error 'PromiseLike' only refers to a type, but is being used as a value here.:

declare global {
    interface PromiseLike<T> {
        handle(): PromiseLike<T>;
    }
}

PromiseLike.prototype.handle = function<T>(this: T):T {
    return this;
}

Obviously the problem here is that PromiseLike is generic. How can I do this properly in typescript?

like image 612
Archeg Avatar asked Sep 26 '18 09:09

Archeg


People also ask

How do you pass a generic type in TypeScript?

Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

What means T in TypeScript?

This article opts to use the term type variables, coinciding with the official Typescript documentation. T stands for Type, and is commonly used as the first type variable name when defining generics. But in reality T can be replaced with any valid name.

What is the use of generics in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

What is the meaning of generic functions?

Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.


1 Answers

Interfaces do not exist at runtime, they are erased during compilation, so setting the value of a function on an interface is not possible. What you are probably looking for is adding the function to Promise. You can do this similarly:

declare global {
  interface Promise<T> {
      handle(): Promise<T>;
  }
}

Promise.prototype.handle = function<T>(this: Promise<T>): Promise<T> {
  return this;
}
like image 185
Titian Cernicova-Dragomir Avatar answered Oct 19 '22 17:10

Titian Cernicova-Dragomir