我可以从另一个接口动态生成一个接口吗?
Can I dynamically gerate a interface from another Interface?
所以我正在尝试在 React 中构建自定义 useForm 挂钩。我想要一个函数,为我的输入提供它需要的所有 Props,它包含在钩子中,目前它看起来像这样:
const getInputProps = (name: string) => {
return {
name: name,
//@ts-ignore
value: values[name],
//@ts-ignore
errorMessages: errorMessages[name],
onChange: onChange,
setValue: (value: string) => {
setValues({ ...values, [name]: value });
},
showErrorMessages: showErrorMessages,
};
};
正如您目前可能知道的那样,我必须抑制值 [name] 上的类型错误,因为 Typescript 实际上不知道名称参数是否是我的值对象中的有效键。
我的值对象是用动态接口声明的,该接口在方法调用时给出:
export function useForm<InitialState>(
initialState: InitialState,
handleSubmit: (e: SyntheticEvent) => void,
validators: { [key: string]: Validator<any>[] }
) {
const [values, setValues] = useState<InitialState>(initialState);
现在我想知道是否有办法从 InitialState 接口的键生成类型或接口。示例:
interface UserFormData {
value1:string;
value2:string;
}
将映射到
type UserFormDataEnum = "value1" | "value2"
然后我可以将其传递给 getInputProps 函数:
const getInputProps = (name:UserFormDataEnum) => {...}
您可以使用 keyof
类型运算符,如下所示:
type UserFormDataEnum = keyof UserFormData
所以我正在尝试在 React 中构建自定义 useForm 挂钩。我想要一个函数,为我的输入提供它需要的所有 Props,它包含在钩子中,目前它看起来像这样:
const getInputProps = (name: string) => {
return {
name: name,
//@ts-ignore
value: values[name],
//@ts-ignore
errorMessages: errorMessages[name],
onChange: onChange,
setValue: (value: string) => {
setValues({ ...values, [name]: value });
},
showErrorMessages: showErrorMessages,
};
};
正如您目前可能知道的那样,我必须抑制值 [name] 上的类型错误,因为 Typescript 实际上不知道名称参数是否是我的值对象中的有效键。 我的值对象是用动态接口声明的,该接口在方法调用时给出:
export function useForm<InitialState>(
initialState: InitialState,
handleSubmit: (e: SyntheticEvent) => void,
validators: { [key: string]: Validator<any>[] }
) {
const [values, setValues] = useState<InitialState>(initialState);
现在我想知道是否有办法从 InitialState 接口的键生成类型或接口。示例:
interface UserFormData {
value1:string;
value2:string;
}
将映射到
type UserFormDataEnum = "value1" | "value2"
然后我可以将其传递给 getInputProps 函数:
const getInputProps = (name:UserFormDataEnum) => {...}
您可以使用 keyof
类型运算符,如下所示:
type UserFormDataEnum = keyof UserFormData