接口中的 TypeScript 通用方法签名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32704645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:05:56  来源:igfitidea点击:

TypeScript Generic Method Signature in Interface

genericstypescript

提问by dacox

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 filterUniquemethod, so it should be able to filter lists of numbers, strings, etc.

它是一种filterUnique方法,因此它应该能够过滤数字、字符串等列表。

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!

干杯!

回答by thoughtrepo

The Ttype isn't defined yet. It needs to be added to the method as a type variable like:

T类型尚未确定。它需要作为类型变量添加到方法中,例如:

filterUnique<T>(array: Array<T>): Array<T>;

Or added to the interface like:

或者添加到界面中,如:

export interface IGenericServices<T> {
    filterUnique(array: Array<T>): Array<T>;
}