Skip to content

Updating property in object gives possible undefined error #111

@Keithcat767

Description

@Keithcat767

Description

If I have an object in my state and I go to update a property on it when doing a full state update in an action, it will show a type error saying the object is possibly undefined, despite it being initialized when the store is created and is not optional in the store's interface.

Steps

Example:

interface TestStore {
  test: { [key: string]: string };
  tester: number;
}

const testStore = createStore<TestStore>(
  {
    test: {
      blah: "abc",
    },
    tester: 123,
  },
  {
    name: "repo",
    immer: true,
    devtools: true,
    persist: {
      enabled: true,
    },
  },
).extendActions(({ set }) => ({
  configureTest: (value: string) => {
    set("state", (draft) => {
      draft.test.blah = value;
      draft.tester = 456;
    });
  },
}));

In this example, tester can be set just fine. But test will throw the following error: TS18048: draft. test is possibly undefined.

Note that this works as expected:

configureTest: (value: string) => {
    set("test", {
      blah: value,
    });
  },

Also, not sure if this is related, or if this isn't something I should be able to do. But I would like to be able to still use immer syntax updating a single item.

set("test", (draft) => {
        draft.blah = value;
      });

Currently, the middleware isn't working and I have to do the following:

set(
        "test",
        produce(get("test"), (draft) => {
          test.blah = value;
        }),
      );

Expectation

I would expect that when I initialize the store with an object and it is not set as optional in my interface, that it is not regarded as possibly undefined when performing updates.

I think it is due to the type of draft being a partial: DraftedObject<Partial<TestStore>>. Should it be a partial if the first argument of set it defined as "state"?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions