dacox
dacox

Reputation: 502

TypeScript Generic Method Signature in Interface

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!

Upvotes: 31

Views: 25139

Answers (2)

Christos Lytras
Christos Lytras

Reputation: 37298

Making williaster's comment an answer as it also covers what many people are seeking for this question.

You can also define a generic for the method of an interface without requiring the generic for the entire interface:

interface MyInterface {
  method: <T>(arg: T) => T;
}

Upvotes: 2

thoughtrepo
thoughtrepo

Reputation: 8383

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

Upvotes: 37

Related Questions