Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type for form.change does not allow nested object keys #391

Open
joshuajaco opened this issue Oct 29, 2020 · 5 comments
Open

Type for form.change does not allow nested object keys #391

joshuajaco opened this issue Oct 29, 2020 · 5 comments

Comments

@joshuajaco
Copy link
Contributor

joshuajaco commented Oct 29, 2020

What is the current behavior?

Setting the value of a nested object results in a typescript error:

form.change('nested.key', value);

results in:

Argument of type 'string' is not assignable to parameter of type ...

What is the expected behavior?

Not sure, maybe it should allow any string since we cannot create a dynamic string type.
Not yet at least maybe something to be revisited in the future,
see: microsoft/TypeScript#6579 and microsoft/TypeScript#41160

Workaround

Casting the string using the as keyword

form.change('nested.key' as keyof FormValues, value);

Sometimes this is not enough because the first parameter is used to infer the type of the second parameter.
Then you will have to cast the value as well:

form.change(
  'nested.key' as keyof FormValues,
  value as FormValues[keyof FormValues],
);

And if the types diverge too much typescript won't allow that and you'll have to cast to unknown first:

form.change(
  'nested.key' as keyof FormValues,
  (value as unknown) as FormValues[keyof FormValues],
);
@rikutiira
Copy link

Any update on this?

@21alexander21
Copy link

btw the flow types allow any string as a field name
https://github.com/final-form/final-form/blob/master/src/FinalForm.js#L698

@xxleyi
Copy link
Contributor

xxleyi commented Jun 5, 2021

Now, with TS 4.3, maybe we can consider some improvement on form.change and some other methods:

interface FormApi<FormValues = Record<string, any>> {
  change: <Path extends AllPathsOf<FormValues>>(
    name: Path,
    value?: Partial<ValueMatchingPath<FormValues, Path>>
  ) => void;
}

We can replace keyof FormValues with pathof FormValues, more things can be found here: microsoft/TypeScript#20423 and here: jaredpalmer/formik#3152

@Dema
Copy link

Dema commented Oct 11, 2021

This won't work because of arrays. I think we should revert types to any

@xxleyi
Copy link
Contributor

xxleyi commented Oct 11, 2021

@Dema Path can handle array, React Hook Form already has this feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants