我正在創建一個簡單的鉤子來通過提供 和 來檢索items選項labelKey物件valueKey。
這是我的鉤子引數界面:
interface IProps<T> {
items: T[];
labelKey: keyof T;
valueKey: keyof T;
}
這就是鉤子本身:
const useOptions = <T extends object>(props: IProps<T>) => {
const { items, labelKey, valueKey } = props;
const options = useMemo<SelectOption[]>(() => {
return items.map((item) => ({
label: item[labelKey],
value: item[valueKey],
}));
}, [items]);
return options;
};
export default useOptions;
最后,這是SelectOption我計劃獲得這種型別的陣列。
export interface SelectOption {
value: number | string;
label: number | string;
}
我是如此接近,但我找不到我在這里錯過的東西。這是我看到的打字稿錯誤:
Type 'T[string]' is not assignable to type 'string | number'.
uj5u.com熱心網友回復:
現在T可以有任何形狀。您只限于T成為一種object型別。但是您正在嘗試將內部T的值分配給SelectOption. 這兩個屬性SelectOption都只接受string或number作為它們的值來解釋錯誤。
我們可以限制T為也只有number | string屬性。
const useOptions = <
T extends Record<string, string | number>
>(props: IProps<T>) => {
/* ... */
};
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533291.html
標籤:反应打字稿反应钩子
上一篇:以編程方式確定html背景顏色
