我正在嘗試創建一個過濾器鉤子,我希望鉤子的引數是資料陣列、要過濾的道具 (filterProp) 和搜索文本。
所以我希望資料是 T[],filterProp 是一個字串,代表 T 的一個鍵,但只有字串值(所以我可以在過濾中對它們執行“toUpper”和“indexOf”。搜索文本只是一個字串。
所以我嘗試了這樣的事情::
export const useFilter = <T, K extends Extract<keyof T,string>>(
data: T[] | undefined,
filterProp: K,
searchText: string
) => {
但是當我嘗試用它“toUppercase”時:
data?.filter((item) => item[filterProp].toUpperCase().indexOf(searchText.toUpperCase()) > -1) ?? [];
它提出了 toUppercase 在型別“T[K]”上不存在。
有人知道如何將 filterProp 限制為表示 T 的字串鍵之一的字串值嗎?
謝謝
uj5u.com熱心網友回復:
你可以約束T有K屬性與string價值:
export const useFilter = <T extends Record<K, string>, K extends PropertyKey>(...
操場
實用程式鏈接:Record<Keys, Type> , PropertyKey
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323614.html
上一篇:Kotlin錯誤Smartcastto'X'是不可能的,因為'state'是一個在嘗試觀察狀態時具有打開或自定義getter的屬性
