Problem Description:
我有一个自定义的React hook useFetchSelectOptions
,可以获取数据并将其格式化为可选选项.根据returnForm
参数,选项需要为SelectOption[] | null
类型或' Record<字符串,字符串>|空,但绝不是两者的混合.
我想确保挂钩内的返回类型options
与指定的returnForm
严格匹配.例如:
- 如果
returnForm
是'arr'
,则选项应为SelectOption[] | null
类型. - 如果
returnForm
是'dict'
,则选项应为Record<string, string> | null
类型.
目前,由于挂钩中的条件格式,options
类型可能是Record<string, string> | SelectOption[] | null
,这可能会导致此挂钩的使用者出现歧义.
Goal:
我想在挂钩内实现一个断言机制,以确保options
严格遵守基于returnForm
参数确定的类型.这样,使用挂钩的消费者就可以自信地依赖推断出的类型,而无需进行额外的类型判断.
Code Sample:
import { useState, useEffect } from 'react';
export interface SelectOption {
label: string;
value: string;
}
// Define a type for the return form
type ReturnForm = 'dict' | 'arr';
export function useFetchSelectOptions<T extends { name: string; id: string }>(
fetchData: () => Promise<T[]>,
returnForm: ReturnForm = 'arr', // Default to array format if not specified
): [T[] | null, SelectOption[] | Record<string, string> | null] {
const [data, setData] = useState<T[] | null>(null);
useEffect(() => {
const fetchDataAndMapToOptions = async () => {
try {
const fetchedData = await fetchData();
setData(fetchedData);
} catch (error) {
console.error('Error fetching data:', error);
setData(null);
}
};
fetchDataAndMapToOptions();
}, [fetchData]);
let options: SelectOption[] | Record<string, string> | null = data
? data.map((item) => ({ label: item.name, value: item.id }))
: null;
// Assertion to strictly type 'options' based on 'returnForm'
if (returnForm === 'dict') {
options = options?.reduce(
(acc, curr) => {
if (curr) {
acc[curr.value] = curr.label;
}
return acc;
},
{} as Record<string, string>,
) ?? null;
}
return [data, options];
}
Additional Notes:
我在useFetchSelectOptions
挂钩中添加了一个基本类型断言,以根据returnForm
参数细化options
的类型.这确保了options
将符合预期的SelectOption[] | null
或Record<string, string> | null
,具体取决于指定的returnForm
.
我正在寻求对这种方法的反馈以及任何潜在的改进或替代策略,以在挂钩的上下文中实现严格输入options
.
感谢您的帮助!