I am trying to define an interface with a few methods, and I would like one of the methods to be generic.
It is a filterUnique
method, so it should be able to filter lists of numbers, strings, etc.
the following does not compile for me:
export interface IGenericServices { filterUnique(array: Array<T>): Array<T>; }
Is there a way to make this compile, or am I making a conceptual mistake somewhere here?
Cheers!
TypeScript - Generic Interface The above IProcessor is a generic interface because we used type variable <T> . The IProcessor interface includes the generic field result and the generic method process() that accepts two generic type parameters and returns a generic type. As you learned, you can use interface as type.
Generic constructors are the same as generic methods. For generic constructors after the public keyword and before the class name the type parameter must be placed. Constructors can be invoked with any type of a parameter after defining a generic constructor.
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.
The T
type isn't defined yet. It needs to be added to the method as a type variable like:
filterUnique<T>(array: Array<T>): Array<T>;
Or added to the interface like:
export interface IGenericServices<T> { filterUnique(array: Array<T>): Array<T>; }
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