Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Generic Method Signature in Interface

Tags:

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!

like image 886
dacox Avatar asked Sep 21 '15 21:09

dacox


People also ask

How do I use generics in interface TypeScript?

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.

How do you use generics in an interface?

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.

How do you pass a generic class as parameter 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 is type 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.


1 Answers

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>; } 
like image 181
thoughtrepo Avatar answered Nov 06 '22 05:11

thoughtrepo