Question: using undefined base object
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.
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 .
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!
See https://github.com/immerjs/immer/issues/292
P.S. optional chaining moved to stage3 last week!
This is not Immer's problem. Give configuration a default value, and use something like dset.
+ 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);
});
};
Duplicate of #337, but that issue never had a proper solution given.