Skip to content

Commit

Permalink
fix(ts): produce() return type
Browse files Browse the repository at this point in the history
The return type of `produce()` was not properly inferred when the producer returned anything other than undefined.
  • Loading branch information
aleclarson committed Jan 14, 2019
1 parent 06c8f6f commit b52b45e
Showing 1 changed file with 6 additions and 13 deletions.
19 changes: 6 additions & 13 deletions src/immer.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,17 @@ export interface Patch {

export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void

/** Includes 1 when `void` or `undefined` exists in type `T` */
type HasVoidLike<T> = (void extends T ? 1 : 0) | (undefined extends T ? 1 : 0)

/** Includes 1 when type `T` is `void` or `undefined` (or both) */
type IsVoidLike<T> =
| (T extends void ? 1 : 0)
| (T extends undefined ? 1 : 0)
| (T extends void | undefined ? 1 : 0)
type IsVoidLike<T> = T extends void | undefined ? 1 : 0

/** Converts `nothing` into `undefined` */
type FromNothing<T> = Nothing extends T ? Exclude<T, Nothing> | undefined : T

/** The inferred return type of `produce` */
type Produced<T, Return> = 1 extends HasVoidLike<Return>
? 1 extends IsVoidLike<Return>
? T
: T | FromNothing<Exclude<Return, void>>
: FromNothing<Return>
export type Produced<T, Return> = IsVoidLike<Return> extends 0
? FromNothing<Return>
: IsVoidLike<Return> extends 1
? T
: T | FromNothing<Exclude<Return, void>>

type ImmutableTuple<T extends ReadonlyArray<any>> = {
readonly [P in keyof T]: Immutable<T[P]>
Expand Down

0 comments on commit b52b45e

Please sign in to comment.