When using react-hook-form
, you can access the dirtyFields
property which indicates updated fields with a value of true.
v = {
username: 'alice',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e5e8ede7e1c4e1fce5e9f4e8e1aae7ebe9">[email protected]</a>',
role: 'USER'
}
dirtyFields = {
username: true
}
In this scenario, the goal is to send only the updated fields (in this case, just the username).
An attempted solution:
type User = {
username: string
email: string
role: 'ADMIN' | 'USER'
}
function submitForm (v: User, dirtyFields: Partial<Record<keyof User, boolean>>) {
const updated: Partial<User> = {}
Object.keys(dirtyFields).forEach(field => {
updated[field] = v[field as keyof User]
})
return updated
}
However, an error occurs at updated[field]
:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Partial<User>'.
No index signature with a parameter of type 'string' was found on type 'Partial<User>'.(7053)