I rethought this issue #91, and found that this is not general enough.
Here I suggest a more general solution that can be applied to arbitrary disjoint union type state and then make us happier with TypeScript + use-immer.
dog is a draft object. We can get its properties in primitive type and use them in rendering and other logics.
The updateDog call without any argument applies the recorded patches and finishes the draft.
I think this design is the most type guard friendly one which is possible in TypeScript.
You can use useImmerDraft not only with nullable types but also with arbitrary disjoint union types.
I have a few minor thoughts on it.
Merge useImmerDraft and useImmer into useImmer
They have very similar interface, so just add an argument to useImmer and let useImmer serve both roles.
function useImmer(initialValue, isDraft = false)
And you can select two options with the value of the second argument isDraft.
However, I don't have an idea of the proper behavior in the case that isDraft is trueandupdater` is a callback, yet.
If the Draft<S> type bothers the users, then let the type being just S
The name useImmerDraft is not that good. I hope there is a better one.
Per Immer philosophy, drafts are expected to be shortlived, to which no references should be hold, and imho the updateDog() call is an anti pattern that is very error prone.
I rethought this issue #91, and found that this is not general enough. Here I suggest a more general solution that can be applied to arbitrary disjoint union type state and then make us happier with TypeScript + use-immer.
https://github.com/bglgwyng/use-immer/blob/use-immer-draft/src/index.ts I wrote PoC of
useImmerDraft
, which returns a draft object and its finish.dog
is a draft object. We can get its properties in primitive type and use them in rendering and other logics. TheupdateDog
call without any argument applies the recorded patches and finishes the draft. I think this design is the most type guard friendly one which is possible in TypeScript.You can use
useImmerDraft
not only with nullable types but also with arbitrary disjoint union types.I have a few minor thoughts on it.
useImmerDraft
anduseImmer
intouseImmer
They have very similar interface, so just add an argument touseImmer
and letuseImmer
serve both roles.function useImmer(initialValue, isDraft = false)
And you can select two options with the value of the second argumentisDraft
. However, I don't have an idea of the proper behavior in the case thatisDraft
is trueand
updater` is a callback, yet.Draft<S>
type bothers the users, then let the type being justS