immer icon indicating copy to clipboard operation
immer copied to clipboard

Question: using undefined base object

Open nse7ens opened this issue 7 years ago • 5 comments

I'm trying to use immer.js to set a property in an object which is possible undefined - as are it's children. Can I ensure the object is initialized somehow?

type Config = {
  personal?: {
    navigate?: boolean;
  }
};

const myFunc = (configuration?: Config): void => {
  const mergedConfig: Config = produce(configuration, (draft): void => {
    draft.personal.navigate = true;
  });
};

Using this code, I receive a typescript error saying Object 'draft' is possibly 'undefined'. Anyway I can solve this?

Thanks.

nse7ens avatar Jun 21 '19 09:06 nse7ens

If you search a bit in the closed issues, I'm pretty confident you'll find a duplicate. Let me know if you don't.

Op vr 21 jun. 2019 11:09 schreef Nick Sevens [email protected]:

I'm trying to use immer.js to set a property in an object which is possible undefined - as are it's children. Can I ensure the object is initialized somehow?

type Config = { personal?: { navigate?: boolean; } }; const myFunc = (configuration?: Config): void => { const mergedConfig: Config = produce(configuration, (draft): void => { draft.personal.navigate = true; }); };

Using this code, I receive a typescript error saying Object 'draft' is possibly 'undefined'. Anyway I can solve this?

Thanks.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/immerjs/immer/issues/390?email_source=notifications&email_token=AAN4NBDKA5MPLHE63YHXGX3P3SLDZA5CNFSM4H2PFNCKYY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4G25HLEA, or mute the thread https://github.com/notifications/unsubscribe-auth/AAN4NBCOFDX55OM52ZODTVTP3SLDZANCNFSM4H2PFNCA .

mweststrate avatar Jun 21 '19 09:06 mweststrate

I've searched quite a bit but couldn't find a solution for me. If you could point me in the right direction would be much appreciated!

nse7ens avatar Jun 21 '19 10:06 nse7ens

See https://github.com/immerjs/immer/issues/292

P.S. optional chaining moved to stage3 last week!

mweststrate avatar Jun 21 '19 12:06 mweststrate

This is not Immer's problem. Give configuration a default value, and use something like dset.

Example

+ import dset from 'dset'
+
-const myFunc = (configuration?: Config): void => {
+const myFunc = (configuration: Config = {}): void => {
   const mergedConfig: Config = produce(configuration, (draft): void => {
-    draft.personal.navigate = true;
+    dset(draft, 'personal.navigate', true);
   });
 };

aleclarson avatar Jun 21 '19 14:06 aleclarson

Duplicate of #337, but that issue never had a proper solution given.

aleclarson avatar Jun 21 '19 14:06 aleclarson