我有一個sortDynamic功能,我試影像這樣動態地對資料進行排序:
const sortDynamic = (key: string, order: string) => {
const sortOrder = order === 'asc' ? 1 : -1;
return (a: ProductMapData, b: ProductMapData) => {
const A = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key];
const B = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key];
if (A < B) {
return sortOrder * -1;
} else if (A > B) {
return sortOrder * 1;
} else {
return 0;
}
};
};
哪里ProductMapData是這樣的界面:
interface ProductMapData {
advanceRevenue: number;
advanceTickets: number;
changeInPeriodRevenue: number;
changeInPeriodTickets: number;
currency: string;
entityRef: string;
eopAdvanceRevenue: number;
eopAdvanceTickets: number;
hallLabel: string;
occurredAt: string | undefined;
playedOffRevenue: number;
playedOffTickets: number;
relatedEventName: string;
thumbnail: string;
timeBegins: string;
timedBeginsBegins: string;
soldTickets: number;
soldRevenue: number;
}
并在此處呼叫該函式:
productMapData.sort(sortDynamic('soldTickets', 'asc'));
一切似乎都很好,但我Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProductMapData'. No index signature with a parameter of type 'string' was found on type 'ProductMapData'.ts(7053)在a[key]和上遇到此錯誤
b[key]。我不知道我做錯了什么。任何幫助將不勝感激。
uj5u.com熱心網友回復:
將您的ProductMapData介面擴展到其他對 key 型別嚴格的介面。值可以是任何型別,您也可以指定值的型別。
下面是為您提供的 ProductMapData 的嚴格介面。您可以為值添加更多型別。
interface IObjectKeys {
[key: string]: string | number | undefined;
}
現在您只需要將您的ProductMapData界面擴展到IObjectKeys.
interface ProductMapData extends IObjectKeys
這將告訴您的實體您的物件只有字串型別的鍵。
播放游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/382655.html
上一篇:暗模式在帶有Next.js和Typescript的TailwindCSSV3中不起作用
下一篇:型別轉換條目值?
