the Draft<T> could not use the keyof T type
Rey-Wang opened this issue · comments
Rey Wang commented
you can see an code example here:
code sandbox
function ChangeState<T extends Record<string, any>, M extends keyof T>(
state: T,
field: M,
value: T[M]
) {
return produce(state, (draftState) => {
draftState[field] = value;
// Type 'M' cannot be used to index type 'Draft<T>'
});
}
the keyof T
should be used by Draft<T>
Michel Weststrate commented
See `castDraft` https://immerjs.github.io/immer/typescript#cast-utilities
…On Thu, Mar 17, 2022 at 11:14 AM Rey Wang ***@***.***> wrote:
you can see an code example here:
code sandbox
<https://codesandbox.io/s/typescript-playground-export-forked-jf764x?file=/index.ts>
function ChangeState<T extends Record<string, any>, M extends keyof T>(
state: T,
field: M,
value: T[M]
) {
return produce(state, (draftState) => {
draftState[field] = value;
// Type 'M' cannot be used to index type 'Draft<T>'
});
}
the keyof T should be used by Draft<T>
—
Reply to this email directly, view it on GitHub
<#918>, or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAN4NBB7VBTQXTJ3GNWS5BDVAMH3HANCNFSM5Q6UMC2A>
.
Triage notifications on the go with GitHub Mobile for iOS
<https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675>
or Android
<https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub>.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>
p2k commented
I'm sorry but how does castDraft
help here? draftState
is already of the type Draft<T>
using the cast would produce Draft<Draft<T>>
.
I have a similar problem:
function ChangeStringState<M extends string>(
state: Record<M, string>,
field: M,
value: string,
) {
return produce(state, (draftState) => {
draftState[field] = value;
// Type 'M' cannot be used to index type 'Draft<Record<M, string>>'
});
}
Luca Fanselau commented
Yeah same here, is there a way to use a generic keyof M
parameter to index the Draft type?