sashaikevich
sashaikevich

Reputation: 197

Why does TypeScript think that my immer draft is undefined?

This makes no sense to me, please help:

I'm updating a typed config.

In my Provider component:

const [data, setData] = useImmer<typeof INITIAL_CONFIG>(INITIAL_CONFIG)
...
function updateField(field: MyConfigKeys, value: MyConfigValues): void 
  setData(draft => {
    draft[field] = value 
  })
}

error:

(parameter) draft: WritableDraft<Partial<MyConfigType>>
Type 'MyConfigValues' is not assignable to type 'undefined'.
  Type 'string' is not assignable to type 'undefined'.ts(2322)

What is going on???

Here's a sandbox with a minimal reproducible example: https://codesandbox.io/s/exciting-keldysh-kxvckq?file=/src/App.tsx (there the error is never, instead of undefined):

Upvotes: 0

Views: 603

Answers (1)

tenshi
tenshi

Reputation: 26324

The problem is that TS does not know that the value should match with the field. You can fix this by making it generic:

function updateField<K extends MyConfigKeys>(field: K, value: MyConfigType[K]): void {
    setData((draft) => {
      draft[field] = value;
    });
  }

Now TS knows that value should match the field.

Playground

Upvotes: 1

Related Questions