當“profile.firstName”作為第二個引數傳遞給函式 onChange 時,我想要避免打字稿錯誤。
錯誤描述
'"profile.firstName"' 型別的引數不能分配給'keyof User' 型別的引數。ts(2345)
將“id”、“groupName”和“description”作為第二個引數傳遞給 onChange 不會導致錯誤。
但是,如果傳遞了“profile.firstName”,則會發生錯誤。
import { useForm } from 'react-hook-form';
import type { CustomNextPage } from 'next';
import { Button, Input } from 'components/Forms';
import { Box } from 'components/Layouts';
export interface User {
id?: string;
groupName?: string;
description?: string;
profile?: {
firstName?: string;
lastName?: string;
email?: string;
};
}
const Filter: CustomNextPage = () => {
const { handleSubmit, setValue, watch } = useForm<User>();
type P = keyof User;
const onChange = (value: string, key: P) => {
setValue(key, value);
};
return (
<>
<Box>
<Input onChange={(e) => onChange(e.target.value, 'id')}>ID</Input>
<Input onChange={(e) => onChange(e.target.value, 'groupName')}>GroupName</Input>
<Input onChange={(e) => onChange(e.target.value, 'description')}>Description</Input>
<Input onChange={(e) => onChange(e.target.value, 'profile.firstName')}>FirstName</Input>
<Box>
<form>
<Button type="submit"></Button>
</form>
</Box>
</Box>
</>
);
};
export default Filter;
<Input
onChange={(e) =>
onChange(
{
...watch().profile,
firstName: e.target.value,
},
'profile',
)
}
>
FirstName
</Input>
'{ firstName: string; 型別的引數 姓氏?:字串 | 不明確的; 電子郵件?:字串 | 不明確的; }' 不能分配給“字串”型別的引數。ts(2345)
<Input
onChange={(e) =>
setValue(
{
...watch(),
profile: {
...watch().profile,
firstName: e.target.value,
},
},
'profile',
)
}
>
FirstName
</Input>
'{ profile: { firstName: string; 型別的引數 姓氏?:字串 | 不明確的; 電子郵件?:字串 | 不明確的; }; id?: 字串 | 不明確的; 組名?:字串 | 不明確的; 描述?不明確的; 描述?:字串 | 不明確的; }' 型別的引數 '"id" | "組名" | “說明” | “個人資料” | "profile.firstName" | "profile.lastName" | "profile.email "profile.email"' 引數不能分配給型別為 '"id" | "groupName" | "description" | "profile.firstName" | "profile.lastName" | "profile.email"' 的引數。 ts(2345)
uj5u.com熱心網友回復:
User有一個profile屬性,它是一個具有該屬性的物件firstName。所以這種方法是行不通的。
您可以執行以下操作:
<Input onChange={(e) => onChange({
...value.profile,
firstName: e.target.value,
}, 'profile')}>FirstName</Input>
(我假設useForm還回傳一個value?)
不過,這有點時髦。而且,onChange.value不再只是一個字串。
我認為您有點沉迷于“便利”功能。
也許只是這樣做:
<Input onChange={(e) => setValue("profile", {
...value.profile,
firstName: e.target.value,
})}>FirstName</Input>
也許只是將其拆分為一個setProfileFirstName功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/503794.html
上一篇:使用useContext和createContext渲染過多
下一篇:使用引數導航在反應中不起作用
