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?
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With