immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there a way to convert object types in TypeScript in produce?

shipurjan opened this issue Β· comments

πŸ™‹β€β™‚ Question

Is there a way to convert objects from one type to another in TypeScript using produce?

Link to repro

https://codesandbox.io/p/sandbox/immer-type-conversion-6629x5?file=%2Fsrc%2Findex.ts%3A53%2C3

Environment

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

I'm using this method as for now:

    const objWithoutId: ObjWithoutId = getSomeObj();
    const objWithId = produce(objWithoutId, (draft: Draft<ObjWithId>) => {
        draft.id = 5;
    }) as ObjWithId;

But maybe there is a better way, without as

No, the design of produce is to always have the same input and output type; it is intended to mutate an existing structure, not a mapping function that produces a new kind of object. So in this case you indeed have to cast or make the input type wide enough to also capture the output.