我正在尝试向我的开源库Angular-Slickgrid添加更多通用类型,这是一个数据网格库。
我为 Column Definitions 定义了一个接口,它可以有多个 Type Column
,我正在向这个Column
接口添加一个新的 Generic Type ,我想在formatter
它本身是 Type 的选项中使用这个新的 Type Formatter
,如下所示。新的通用类型基本上是告诉格式化程序,它可能是项目对象的类型。
export interface Column<T = any> {
field: string;
// oops that was a typo
// formatter?: Formatter: T;
// correct code is actually this
formatter?: Formatter<T>;
}
定义Formatter
如下
// add Generic Type for the item object
export declare type Formatter<T = any> = (row: number, cell: number, value: any, columnDef: Column, item: T) => string;
现在我正在尝试通过创建一个ReportItem
传递给的接口来使用新的泛型,columnDefinitions
以便我可以(希望)ReportItem
在我的Formatter
interface ReportItem {
title: string;
duration: number;
cost: number;
percentComplete: number;
start: Date;
finish: Date;
effortDriven: boolean;
}
const customEditableInputFormatter: Formatter = <T = any>(row: number, cell: number, value: any, columnDef: Column, item: T) => {
// I want the `item` to be of Type ReportItem but it shows as Type any
// item.title
};
export class MySample {
columnDefinitions: Column<ReportItem>[];
initializeGrid() {
this.columnDefinitions = [
{
id: 'title', name: 'Title', field: 'title', sortable: true, type: FieldType.string,
formatter: customEditableInputFormatter,
}
];
}
}
如果我将鼠标悬停在该formatter
属性上,我会Formatter<ReportItem>
通过智能感知(在 VSCode 中)看到正确的内容。
但是如果我将鼠标悬停在自定义格式化程序本身上,我会得到Formatter<any>
所以我的问题是如何对其进行编码,以便它在我的外部格式化程序中真正采用正确的类型ReportItem
,我希望我的外部格式化程序是 TypeFormatter<ReportItem>
而不是Formatter<any>
. 我开始学习泛型,我发现它非常强大,但仍有一些方法可以学习它们。
感谢您提供的任何帮助。
编辑 1
我还尝试在自定义格式化程序 ( ) 上替换<T = any>
by并在使用时添加 a ,但它仍然显示为<T>
const customEditableInputFormatter: Formatter = <T>...
customEditableInputFormatter as Formatter<ReportItem>
T
any