I'm trying to describe the type of the function which handles change event to reflect the value in the state.
The desired implementation would look like:
handleChange: ChangeHandler<State> = field => value =>
this.setState({ [field]: value });
Given state:
interface State {
title: string;
description: string | null;
}
One could pass this function to the component as:
<TextComponent onChange={this.handleChange('title')} />
My best attempt to tackle this problem was to create the following type:
type ChangeHandler<S> = <K extends keyof S, V extends S[K]>(key: K) => (value: V) => void;
However, this seems to work only if all properties of the state are optional. I can't manage to get this to work with state of both optional and non-optional properties.
Compiler error:
[ts] Argument of type '{ [x: string]: V; }' is not assignable to parameter of type 'State | ((prevState: Readonly, props: Readonly) => State | Pick | null) | Pick<...> | null'.
Type '{ [x: string]: V; }' is missing the following properties from type 'Pick': title, description [2345]