When I have an object which has nested optional fields, like:
type FormState = {
aaa?: {
bbb?: {
ccc?: number
}
}
}
When I want to set value to aaa.bbb.ccc
in typescript, I have to:
import produce from "immer";
const formState: FormState = {}
const target = produce(formState, draft => {
draft.aaa = draft.aaa ?? {}
draft.aaa.bbb = draft.aaa.bbb ?? {}
draft.aaa.bbb.ccc = 1;
})
Is there any way to make it simpler?
The optional chaining syntax isn't work here:
draft?.aaa?.bbb?.ccc = 1; // compilation error
A small demo: https://github.com/freewind-demos/typescript-immer-set-value-to-nested-optional-fields-demo