I have two functions that duplicate code except for the name of the key in the call to setState()
:
fooFunc(value: Moment) {
if (condition){
this.setState({foo: value});
} else {
doSomethingElse();
this.setState({foo: undefined});
}
}
barFunc(value: Moment) {
if (condition){
this.setState({bar: value});
} else {
doSomethingElse();
this.setState({bar: undefined});
}
}
How can I refactor this to a single method that accepts the name of the key as a parameter and sets the state accordingly?
// something like this, but this doesn't work:
parameterizedFunc(name: string, value: Moment){
if (condition){
this.setState({[name]:value});
} else {
this.setState({[name]:undefined});
}
}
When using the above technique, I am getting the following (redacted) error message:
"Argument of type '{ [x: string]: moment.Moment; }' is not assignable to parameter of type 'MyState | Pick<MyState, keyof MyState> | ((prevState: Readonly<...>, props: Readonly<...>) => MyState | ... 1 more ... | null) | null'.\n Type '{ [x: string]: Moment; }' is missing the following properties from type 'Pick<MyState, keyof MyState>': aList, bList, cList, dList, and 8 more."