我有三个接口:
A.ts
export interface A {
requestID: number;
createdUser: string;
createdDate: string;
text: string
}
字符串
B.ts
export interface B {
requestID: number;
createdUser: string;
createdDate: string;
department: string;
emailID: string;
}
型
AB.ts
export interface AB extends A, B {
requestType: string;
assignedUser: string;
}
型
现在,我在泛型方法中使用这些接口来执行一些排序功能:
function sort<T extends AB | A | B>(requests: T[], columnName: string) {
switch columnName {
case "requestID": {
requests.sort((a, b) => a.requestID > b.requestID ? 1 : -1);
} case "requestType": {
requests.sort((a, b) => a.requestType > b.requestType ? 1 : -1);
break;
} case "text": {
requests.sort((a, b) => a.text > b.text ? 1 : -1);
break;
} case "department": {
requests.sort((a, b) => a.department > b.department ? 1 : -1);
break;
}
}
}
型
但是,我得到了下面的错误:
Property 'requestType' does not exist on type 'AB | A | B'.
型
由于requests
的类型是T
,这是一个泛型(它是从AB
,A
和B
扩展而来的),我相信它应该有requestType
属性,它不应该抛出这个错误。我哪里错了吗?
1条答案
按热度按时间f45qwnt81#
您的情况非常简单,不需要以不同的方式处理不同的列
只需要使用一个完全通用的排序器:
字符串
或者在你的自定义排序器中调用它(添加了
K extends keyof T
)来排序