You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[@types/react] cannot setState with dynamic key name type-safe #26635
If you do not mention the authors the issue will be ignored.
I cannot call setState with an object being created from computed property name with type-safety:
typeState={username: string,password: string};typeStateKeys=keyofState;classAextendsReact.Component<{},State>{dynSetState(key: StateKeys,value: string){this.setState({[key]: value// Error here. Pretty sure key is in StateKeys});}}
I do aware of #18365, and the workaround in #18365 (comment) . However, when using the workaround, Typescript doesn't error out when it should:
dynLooselySetState(key: string,value: string){this.setState(prevState=>({
...prevState,[key]: value// No error here, but can't ensure that key is in StateKeys}));}
Reacted by Rohan Ray, Jarda Kotěšovec, Nacho Justicia, Mig Coder, Lee Fernandes, Ian Kemp, Alex Coady, Zheeeng, Carlos Pérez Gutiérrez, Sebastian "Sebbie" Silbermann and 53 more
This is a limitation of the compiler itself, inferred types via computed property keys do not support union types, it only supports string, number, symbol or a single literal of those 3, if it detects that it's a union of any of those it will just coerce it into the general string type. The workaround here would be to coerce the object:
This will still give an error appropriately if the value is not in the set of possible property value types, but will not give you an error if the keys are not within the set of possible property keys.
Reacted by BatAmar Battulga, Zheeeng, Patrick Vice, 윤영채, Kumassy, Mahdi Abdi, slch, Walerian Sobczak, John Darryl Pelingo, Christian Medina and 68 more
Reacted by Jean Francisco Flores Gatto, Roman Travnikov and Shirel Garber
Reacted by Mosh Feu, Vlad Shulha, Abhijit, Frederic MAMATH, Kirill Anisimov, Pierre-Olivier Mauguet, Leo Borai, Giedo Mak, liulin, YongEun Choi and 5 more
exactly what @ferdaber although IMHO casting stuff like this is not very "good pattern", overall you should prefer updating state via callback pattern which again adheres to best practices, like extracting that callback outside the class to pure easy to test function :)
I have not found related issue about this limitation in typescript repo.. Any chance you know if this has been discussed (and where) in typescript repo? Basically wondering if there are some plans to address this in future typescript versions.
Thanks!
Indeed, what I'm trying to accomplish is to do something like this: https://reactjs.org/docs/forms.html#handling-multiple-inputs
Which will make it easier to deal with a form with multiple inputs. I may still have to make sure that the "name" attribute is what we expect, but after that type-safety should works.
Reacted by Lee Fernandes, Ian Kemp, Bruno Bigras, Steve Lambe, Shuang, Frank Hangler, f-engstrom and Ivan Lednev
That warned if key was a boolean, but not if it was a number!
So I went for this shorter solution:
this.setState<never>({[key]: value})
This warns if key is a boolean or a number.
Reacted by Gianfranco P, Abhijit, Dmytro Bondarenko, Mohammad Tamimi, Edvins Antonovs, Cristi, DrakeXiang, Inamul, Saravanan Nandhan, boraoren and 8 more
Reacted by Saravanan Nandhan, Genaro Camele, Jean Francisco Flores Gatto and Mirel Bițoi
Reacted by Abhijit, Mohamed Feddad, Genaro Camele and Mirel Bițoi
For others looking at this and trying to apply it to their own state types, note that the type of value in the original post and responses is only string because all property types in State are string. It might be better to avoid using any or additional casting when other types are involved, and instead restricting the types such that the type of value corresponds to its type matching the key type.
interfaceState{name: string;age: number;}typeStateKeys=keyofState;functiondynSetState<KextendsStateKeys>(key: K,value: State[K]){this.setState({[key]: value});// fails; if only this worked...this.setState({[key]: value}asPick<State,K>);// clean cast worksthis.setState((s,_)=>({ ...s,[key]: value}));// avoids cast, but changes js}dynSetState("name","a");// works as expecteddynSetState("name",1);// fails as expecteddynSetState("age","a");// fails as expecteddynSetState("age",1);// works as expected
Why is #26635 (comment) working? I mean the key is still a union type?
It works because the type of { ...prevState } will sufficiently match State, basically because we have at least all the properties of state. It might help to understand why it doesn't work without it. The root of the issue is that the type of the object created: { [key: K]: State[K] } is not specific enough; it is { [x: string]: State[K] } which can't cast the key string to a keyof State.
Although this gives me the following error in the console:
Warning: Acomponentischangingacontrolledinputoftypepasswordtobeuncontrolled.Inputelementsshouldnotswitchfromcontrolledtouncontrolled(orviceversa).Decidebetween using acontrolledoruncontrolledinputelementforthelifetimeofthecomponent.
Alternative Solution (Cheating) With Console Errors:
Hi thread, we're moving DefinitelyTyped to use GitHub Discussions for conversations the @types modules in DefinitelyTyped.
To help with the transition, we're closing all issues which haven't had activity in the last 6 months, which includes this issue. If you think closing this issue is a mistake, please pop into the TypeScript Community Discord and mention the issue in the definitely-typed channel.
Activity
ferdaber commentedon Jun 25, 2018
This is a limitation of the compiler itself, inferred types via computed property keys do not support union types, it only supports
string,number,symbolor a single literal of those 3, if it detects that it's a union of any of those it will just coerce it into the generalstringtype. The workaround here would be to coerce the object:This will still give an error appropriately if the value is not in the set of possible property value types, but will not give you an error if the keys are not within the set of possible property keys.
Hotell commentedon Jun 26, 2018
exactly what @ferdaber although IMHO casting stuff like this is not very "good pattern", overall you should prefer updating state via callback pattern which again adheres to best practices, like extracting that callback outside the class to pure easy to test function :)
Good:
Better:
jardakotesovec commentedon Jul 10, 2018
I have not found related issue about this limitation in typescript repo.. Any chance you know if this has been discussed (and where) in typescript repo? Basically wondering if there are some plans to address this in future typescript versions.
Thanks!
ferdaber commentedon Jul 10, 2018
Here is the discussion, the design notes from the TS team, and an attempt at fixing it (which I believe was retracted for a future version):
microsoft/TypeScript#13948
microsoft/TypeScript#18155
microsoft/TypeScript#21070
peat-psuwit commentedon Jul 12, 2018
Indeed, what I'm trying to accomplish is to do something like this: https://reactjs.org/docs/forms.html#handling-multiple-inputs
Which will make it easier to deal with a form with multiple inputs. I may still have to make sure that the "name" attribute is what we expect, but after that type-safety should works.
joeytwiddle commentedon Apr 24, 2019
I had to add
as unknownto @ferdaber's solution:That warned if
keywas a boolean, but not if it was a number!So I went for this shorter solution:
This warns if
keyis a boolean or a number.neomib commentedon Jul 23, 2019
Why is #26635 (comment) working? I mean the key is still a union type?
damir-manapov commentedon Feb 25, 2020
May be this will help you
jinggk commentedon Apr 16, 2020
Is there any progress in this issue?
n3rd253 commentedon May 23, 2020
I was able to get this working
arinwt commentedon Jun 18, 2020
For others looking at this and trying to apply it to their own state types, note that the type of
valuein the original post and responses is onlystringbecause all property types inStatearestring. It might be better to avoid usinganyor additional casting when other types are involved, and instead restricting the types such that the type ofvaluecorresponds to its type matching the key type.It works because the type of
{ ...prevState }will sufficiently matchState, basically because we have at least all the properties of state. It might help to understand why it doesn't work without it. The root of the issue is that the type of the object created:{ [key: K]: State[K] }is not specific enough; it is{ [x: string]: State[K] }which can't cast the keystringto akeyof State.codingwithmanny commentedon Jun 19, 2020
Just adding to @arinwt as an another example.
TL;DR: Final Solution At Bottom
Expanded Solution With Console Errors:
Although this gives me the following error in the console:
Alternative Solution (Cheating) With Console Errors:
Also gives the warning too.
Final Solution No Errors:
orta commentedon Jun 7, 2021
Hi thread, we're moving DefinitelyTyped to use GitHub Discussions for conversations the
@typesmodules in DefinitelyTyped.To help with the transition, we're closing all issues which haven't had activity in the last 6 months, which includes this issue. If you think closing this issue is a mistake, please pop into the TypeScript Community Discord and mention the issue in the
definitely-typedchannel.