Immer: Types are not recognised when using produce function in react setState

Created on 5 Apr 2019  路  8Comments  路  Source: immerjs/immer

馃悰 Bug Report

I am using immer in typescript project with react setState, everything was ok until today were typescript start throwing errors and complaining about types in the produce function (draft).
it's complaining that the 'draft' is possibly 'null' and therefore not recognizing the types.

To Reproduce

please have look at the following link:

https://codesandbox.io/s/7zk7z28o11

please open the link in the Chrome browser and wait for Ts to throw the errors, it may be a slow process in the browser.

Expected behavior

the draft should recognize the state types as it was before, but somehow it's not working anymore, I can explicitly set the type 'draft: IState', and the problem will go away.

Environment

Ts Version = 3.3.4000
windows 10

Thanks,

bug typescript

All 8 comments

apparently, the problem is related to the latest vscode update and ts 3.4

I might be wrong, but I don't think curried producers ever inferred the draft type. You claim otherwise. Can you provide a git repository where it works as expected?

after some digging, I have realised that the problem is related to the strict option in tsconfig file; when strict option is true the type inferring works fine in TS 3.3; however, it doesn't work with TS 3.4.

To reproduce (working version):

  1. git clone https://github.com/Cyrus-d/react-webpack-typescript-starter
  2. yarn
  3. yarn build

the project should build with no error.

Not working after:

  1. yarn add typescript (will add TS 3.4)
  2. yarn build

you will get Object is possibly 'null' error.

Now setting draft: IState, won't pass the build either and thats because of the strict option is on, and you will get following error message:

Argument of type '(draft: IState) => void' is not assignable to parameter of type '(this: { count: number; } | {} | null, draft: { count: number; } | {} | null) => void

now the only option for me is to set the draft type to any.

hope it helps.

I'll check if we can fix this as part of #325

Took a closure look, but TypeScript doesn't infer types from the outside in (beyond a direct callback), but always from "inside out", so with TS, the only way the fix the above is to type the recipe explicitly: produce((draft: IState) => {

@mweststrate Hey! Using TS 4.0.3 and immer v2.1.5 (and before), I'm getting inferred types for draft:
image
https://codesandbox.io/s/adoring-https-rsgqg?file=/src/App.tsx

Changing it to immer v8.0.0 we lose the type for draft:
image
https://codesandbox.io/s/flamboyant-lehmann-ms3fw?file=/src/App.tsx

What's the correct way to handle this, and to use immer with React setState()?

@oscar-b this issue is closed for more than a year. Open a new one and follow the template.

Was this page helpful?
0 / 5 - 0 ratings