immerjs / immer

Create the next immutable state by mutating the current one
https://immerjs.github.io/immer/
MIT License
27.5k stars 850 forks source link

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

Closed shipurjan closed 6 months ago

shipurjan commented 6 months ago

🙋‍♂ 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

shipurjan commented 6 months ago

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

mweststrate commented 6 months ago

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.