我对数组输入的泛型类型有疑问。我有一个名为useForm
的函数,它接受以下选项
export interface DataType {
[key: string]: FieldValue;
}
export type FieldValue = boolean | string | string[] | number | {};
export default function useForm<Data extends DataType>(
{ mode, validationSchema, defaultValues, validationFields }: Props<Data> = {
mode: 'onSubmit',
defaultValues: {},
},
): UseFormFunctions<Data> {
}
export interface Props<Data> {
mode: 'onSubmit' | 'onBlur' | 'onChange';
defaultValues?: { [key: string]: any };
validationFields?: string[]; // how do i use generic type here to only allow key from FormData
validationSchema?: any;
}
type FormData = {
firstName: string,
lastName: string,
}
const { register } = useForm<FormData>({
validationFields: ['test'] // should throw error because it's not firstname or lastname
})
我希望它在找不到FormData类型时抛出类型错误。
答案 0 :(得分:2)
您可以使用keyof
来获取Data
中的键的并集:
export default function useForm<Data extends DataType>(
{ mode, validationSchema, defaultValues, validationFields }: Props<Data> = {
mode: 'onSubmit',
defaultValues: {},
},
): UseFormFunctions<Data> {
return null!;
}
export interface Props<Data> {
mode: 'onSubmit' | 'onBlur' | 'onChange';
defaultValues?: { [key: string]: any };
validationFields?: Array<keyof Data>; // how do i use generic type here to only allow key from FormData
validationSchema?: any;
}
type FormData = {
firstName: string,
lastName: string,
}
const { register } = useForm<FormData>({
mode: 'onBlur',
validationFields: ['test'] // error now
})