Similar to React, I am interested in working with states in a custom library. The current class I have is as follows:
export abstract class Room<State> {
protected state: State;
protected setState<Key extends keyof State>(
state: ((previousState: Readonly<State>) => Pick<State, Key> | State)
| (Pick<State, Key>)
) {
if (typeof state === "function") {
// TypeScript is complaining about the call signature of 'state', even though I expected to be able to distinguish between both types of the state argument. Removing the final | State at the end of the state type makes it work, but Intellisense in VS Code no longer offers key completion in lines like this.setState({ foo: 1 });
const newState = state(this.state);
// ...
}
// ...
}
// ...
}
In the comment, TypeScript is merging the second type of state to State & Function. Why is this happening? Is there a safe way to rewrite this?