[英]Unable to define type for generic compare function with typescript
[英]Define generic typescript sort function of a certain type
我有一堆對象,所有對象都具有Moment
類型的屬性,但是鍵的名稱不同。
我正在嘗試使用typescript編寫一個小的實用函數,在其中可以對任何這些對象進行排序。 可以在正確的方向使用一些推子。
interface ExampleType1 {
startDate: Moment;
// ... other members
}
interface ExampleType2 {
dueDate: Moment;
// ... other members
}
interface ExampleType3 {
createdAt: Moment;
}
我希望我的函數看起來像這樣(半偽代碼):
function sortByDateAsc(data: ATypeThatHasAMoment[], keyName: KeyToTheMomentTypeWithinATypeThatHasAMoment) {
return data.sort((a, b) => {
// whatever sort logic i use here
// accessing the Moment object via a[keyName] and b[keyName]
}
}
我一直在擺弄這樣的東西
function sortByDateAsc<T, K extends keyof T>(data: T[], dateKey: K);
盡管函數T [K]中沒有類型? 我不確定如何告訴函數“ T [K]必須為Moment類型”
您可以這樣進行:
declare function sortByDateAsc<K extends keyof any, T extends Record<K, Moment>>(
data: T[],
dateKey: K
): T[];
其中將T
約束為T[K]
為Moment
。 這具有易於定義的優點,並且可以工作……但是,它可能不會給出很好的IntelliSense提示。 例如:
declare const ex1arr: ExampleType1[];
sortByDateAsc(ex1arr, "startdate"); // error
// ~~~~~~ <-- "startdate" not in ExampleType1
這是作為ex1arr
上的錯誤ex1arr
,而不是"startdate"
上的錯誤給出的。 此外,它不建議將"startDate"
作為更正。
相反,您可以使用更復雜的條件類型,如下所示:
type KeysMatching<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T];
declare function sortByDateAsc<T extends any, K extends KeysMatching<T, Moment>>(
data: T[],
dateKey: K
): T[];
代替約束T
,該簽名將K
約束為T[K]
匹配Moment
的密鑰。 現在,同一示例為您提供了更好的錯誤:
declare const ex1arr: ExampleType1[];
sortByDateAsc(ex1arr, "startdate"); // error
// ~~~~~~~~~~~ <-- does not match "startDate"
當您開始鍵入dateKey
參數時,它具有更好的IntelliSense提示(建議使用"startDate"
)。
兩種方法都應該起作用。 希望能有所幫助。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.