Immer: Type inference bug

Created on 4 Jun 2019  路  4Comments  路  Source: immerjs/immer

馃悰 Bug Report

A draftState must be typed.

It seems draftState cannot be inferred.

Link to repro (highly encouraged)

https://codesandbox.io/s/immer-sandbox-ys4u3

bug

All 4 comments

Previous (without a repro) https://github.com/immerjs/immer/issues/376#event-2387683798

Currently, the Draft<T> type can't detect when an object type is "immerable" (that is, whether or not it can be drafted), because of TypeScript's structural nature. I opened https://github.com/microsoft/TypeScript/issues/29063 in hopes that we can work around that.

Basically, the HTMLElement type gets wrapped with Draft<T>, which creates a type that is incompatible with HTMLElement. We could add a special case for HTMLElement and friends, but only if there's a use case that makes (a lot of) sense. For now, I recommend keeping class instances out of your Immer state, unless they are immerable (and HTMLElement is not immerable).

Luckily, your workaround of explicitly-typed draft argument isn't too horrible. 馃槅

I think this is the same as all other type bug reports you will find in this repo; basically immer can take two approaches:

  1. Given any T, it will remain T in the producer. That means if T is a read only data type, it would be unmutable in the producer (type wise)
  2. Given any T, it will become Draft<T>, to make sure it is mutable.

Immer opted for option 2.
However, Draft<T>'s are assignable to T, but since T the inverse is not true (T not assignable to Draft<T>, for example, for arrays .push would be missing), and for issues mentioned above, it means at moments you will have to type things explicitly. Sadly we can't really help that, in either solution people will have to give type hints occasionally.

Thank you, guys.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

martinkadlec0 picture martinkadlec0  路  3Comments

jameskfry picture jameskfry  路  3Comments

yuanalexwu picture yuanalexwu  路  5Comments

cakoose picture cakoose  路  6Comments

CodingPapi picture CodingPapi  路  7Comments