mutative
mutative copied to clipboard
How to add new keys?
Did not find any information about this usecase in the docs
Is there any way to do something like this:
const base = { a: 1 };
const add_b_key = create(base, (draft) => {
draft.a = 2;
draft.b = 1;
});
getting error on b: Property 'b' does not exist on type 'DraftedObject<{ a: number; }>'.
Would love to use mutative notation for both new and existing keys.
Are we expected to spread operate the base for new keys?
const base = { a: 1 };
const add_b_key = create({...base, b: 1}, (draft) => {
draft.a = 2;
});
Or I'm missing an utility/setting
hi @qcho, you should be explicit with your type declarations. Otherwise, regardless of whether you use Mutative, you will get a type error. Like this,
const base = { a: 1 };
base.a = 2;
// Property 'b' does not exist on type '{ a: number; }'.(2339)
base.b = 1;
so you can explicitly declare the correct type.
const base: { a: number; b?: number } = { a: 1 };
const add_b_key = create(base, (draft) => {
draft.a = 2;
draft.b = 1;
});