31

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!

2 Answers 2

37

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>;
}
Sign up to request clarification or add additional context in comments.

2 Comments

In case it helps others, 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; }
@williaster If you would post that as an answer you would get my upvote, because that syntax was exactly what I was looking for when I landed on this page. Thanks! Small correction, change : to =>: <T>(arg: T) => T;
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.