Browse files

Minor correction to TypeScript `setState` type

Instead of allowing a `Partial<State>` to when calling `setState`, allow `Pick<State, K>` instead. Honestly, it looks like someone meant to do this in the first place but missed it, as the `K` generic type was already declared.

This is a legitimate bug. Imagine that state is of type `{ x: number }`, and I try to call `setState({ x: undefined })`.
With `Partial`, that's totally valid, because `Partial` creates a new type with the same keys, but each "optional". Of course, optional allows `undefined`.
`Pick`, on the other hand, maps to a new type that only has a subset of the original keys but maintains the type of the remaining keys. So `{}` would be a valid argument, because it has the empty set of keys, but `{ x: undefined }` is out because `x` still needs to be a number.

This is in line with the React version:
  • Loading branch information...
BrandonWilliamsCS authored and jamiebuilds committed Jul 6, 2018
1 parent cb67dbf commit b5d12e187ab456e84f9bff388715b2f9d56e65cc
Showing with 2 additions and 2 deletions.
  1. +2 −2 src/unstated.d.ts
@@ -4,8 +4,8 @@ export class Container<State extends object> {
state: State;
setState<K extends keyof State>(
| ((prevState: Readonly<State>) => Partial<State> | State | null)
| (Partial<State> | State | null),
| ((prevState: Readonly<State>) => Pick<State, K> | State | null)
| (Pick<State, K> | State | null),
callback?: () => void
): Promise<void>;
subscribe(fn: () => any): void;

0 comments on commit b5d12e1

Please sign in to comment.