Skip to content

The return type of the produce method will have an additional undefined聽#1003

Description

@JaneSu

馃檵鈥嶁檪 Question

A clear and concise description of what the question is. In general we recommend to use Stack Overflow for questions. Questions typically are processed with less priority.

import { produce } from 'immer';

const func = produce((state: Record<string, string> = {}): Record<string, string> => {
  return state;
});

In the above code, I expect the type of the func to be Record<string, string>, but the actual type check returns Record<string, string> | undefined, how can I avoid the undefined?

image

This problem only occurs in 9.x versions

Link to repro

https://codesandbox.io/s/immer-sandbox-forked-n1okz2?file=/src/index.ts

Environment

We only accept questions against the latest Immer version.

  • Immer version:
  • Occurs with setUseProxies(true)
  • Occurs with setUseProxies(false) (ES5 only)

Activity

  1. childrentime commented on Feb 5, 2023

    @childrentime
    Contributor

    remove the default assignment and it will work. state = {} will inner state to Record<string,string> | undefined.

  2. childrentime commented on Feb 5, 2023

    @childrentime
    Contributor
    type InferCurriedFromRecipe<
    	Recipe,
    	UsePatches extends boolean
    > = Recipe extends (draft: infer DraftState, ...args: infer RestArgs) => any // verify return type
    	? ReturnType<Recipe> extends ValidRecipeReturnTypePossiblyPromise<DraftState>
    		? (
    				base: Immutable<DraftState>,
    				...args: RestArgs
    		  ) => PromisifyReturnIfNeeded<DraftState, Recipe, UsePatches> // N.b. we return mutable draftstate, in case the recipe's first arg isn't read only, and that isn't expected as output either
    		: never // incorrect return type
    	: never // not a function
    
     
  3. childrentime commented on Feb 6, 2023

    @childrentime
    Contributor

    @mweststrate maybe produce function should explicitly return draft to avoid this situation?

  4. mweststrate commented on Feb 6, 2023

    @mweststrate
    Collaborator

    recipes should not use a default argument, as they are never seen by produce. produce would indeed in such a case indeed return undefined, so the inferred type is correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions