由于我是TS的新手,我很可能会错误地处理这个问题,但是我想知道我是否有某种通用类型可以通过它传递一个看起来像是{[key: string]: string | boolean}
可以知道任何特定类型的接口的接口。使用该泛型的函数中的值。
例如,我有一个类似的界面:
export interface Address {
addressId: string;
firstName: string;
lastName: string;
addressType: string;
addressLine1: string;
addressLine2: string;
city: string;
state: string;
country: string;
zipCode: string;
email1: string;
phone1: string;
primary: boolean;
nickName?: string;
}
我正在尝试做这样的事情:
function useForm<T>(initialValues: T) {
const [form, setForm] = useState<T>(initialValues);
const field = (key: keyof T) => {
const setValue = (newValue: T[keyof T]) => {
const newState = {
...form,
[key]: newValue
}
setForm(newState);
}
const value = form[key];
return {
value,
setValue
};
}
return {
form,
field,
};
}
我的textField有一个看起来像这样的接口
interface TextFieldProps {
field: {
setValue: (value: string) => void;
value: string;
};
label?: string;
placeholder?: string;
containerStyle?: ViewStyle;
}
以我的形式看起来像
const {form, field} = useForm<Address>(someInitialAddress);
...
<TextField field={form("FirstName")} />
...
如果您尝试加载接口上不存在的字段,则已经引发了类型错误,但是我想提防确保您没有将基于布尔值的值或其他内容加载到该字段中,而我当前收到此类型错误: Type '{ value: string | boolean | undefined; setValue: (newValue: string | boolean | undefined) => void; }' is not assignable to type '{ setValue: (value: string) => void; value: string; }'.
任何帮助将不胜感激,谢谢!
看来这符合我的需求:
function useForm<T>(initialValues: T) {
const [form, setForm] = useState<T>(initialValues);
function field<K extends keyof T>(key: K) {
function setValue<PropType extends T[K]>(newValue: PropType) {
const newState = {
...form,
[key]: newValue,
};
setForm(newState);
};
const value = form[key];
return {
value,
setValue,
};
};
return {
form,
field,
};
}
当这样使用时:
interface Address {
addressId: string;
firstName: string;
lastName: string;
addressType: string;
addressLine1: string;
addressLine2: string;
city: string;
state: string;
country: string;
zipCode: string;
email1: string;
phone1: string;
primary: boolean;
nickName?: string;
}
...
const { field, onSubmit } = useForm<Address>(someInitialAddress);
...
<TextField
field={field('firstName')}
label="First Name"
placeholder="First Name"
/>
This returns the field prop as:
field: {
setValue(value: string): void;
value: string;
};
...
<CheckboxField
field={field('primary')}
label="Use as my primary address for Billing and Shipping"
/>
This returns the field prop as:
field: {
setValue(value: boolean): void;
value: boolean;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句