In React, the Component definition looks something like this:
class Component<S> {
state:S;
setState(state:S):void;
}
And you define a component like this:
interface MyState {
name: string;
age: number;
}
class MyComponent extends Component<MyState> { }
Now the issue I have is that in the React API setState is supposed to be called with a partial state object, representing properties to be updated, like this:
setState({name: "Aaron"});
Note that age is not declared. The problem I have is that TypeScript doesn't allow this, it gives an assignment error like Property 'age' is missing. By my understanding, the react.d.ts definition is wrong in this sense. But is there a solution?
I tried this:
setState({name: "Aaron"} as MyState);
But this gives the same error, even though it works in the Playground without giving an error. Why does it work in the Playground? Any ideas?
Object.assign(fully working with type-checking and without having to create interface declarations with optional members), but I'm still unsure how. The very same code works in one project but not in another. Once I figure it out I'll post the update.