【发布时间】:2021-01-30 19:39:48
【问题描述】:
我正在学习 TypeScript,目前我正在尝试创建一个通用的排序函数。
我有两个接口:
interface RefreshToken {
client_icon?: string;
client_id?: string;
client_name?: string;
created_at?: string;
id?: string;
is_current?: boolean;
last_used_at?: string;
last_used_ip?: string;
type: "normal" | "long_lived_access_token";
}
interface PersistentNotification {
created_at: string;
message?: string;
notification_id?: string;
title: string;
status?: "read" | "unread";
}
而我目前的功能是这样的:
function SortByDateAscending<T, K extends keyof T>(values: T[], key: K) {
const compare = (first: T, second: T) => {
const timeA = first[key] ? new Date(first[key]) : 0;
const timeB = second[key] ? new Date(second[key]) : 0;
if (timeA < timeB) {
return 1;
}
if (timeA > timeB) {
return -1;
}
return 0;
};
return values.sort(compare);
}
上述代码有效,但我收到警告:
没有重载匹配这个调用。重载 1 of 5, '(value: string | 号码 |日期):日期',给出了以下错误。 'T[K]' 类型的参数不能分配给 'string | 类型的参数号码 |日期'。 类型 'T[keyof T]' 不可分配给类型 'string |号码 |日期'。 键入'T[字符串] | T[号码] | T[symbol]' 不能分配给类型 'string |号码 |日期'。 类型 'T[string]' 不能分配给类型 'string |号码 |日期'。 类型 'T[string]' 不可分配给类型 'Date'。 类型 'T[keyof T]' 不能分配给类型 'Date'。 类型 'T[K]' 不能分配给类型 'Date'。
不确定是否有办法添加一个约束,告诉T[K] 必须是string | number | Date
这是我的测试项目:https://stackblitz.com/edit/typescript-yzualr
我目前只传递字符串类型(一个是可选的),但也会使用日期,所以如果 T[K] 是日期,我不应该使用new Date。
我想避免对接口进行任何更改,当然还要为每种类型创建单独的函数。
【问题讨论】:
标签: typescript typescript-generics