How to narrow down context type by state in xstate v5? (typestates or something else?) #4958
Unanswered
nickredmark
asked this question in
Q&A
Replies: 1 comment
-
Being able to narrow down the context type by state would be useful. As a workaround for actor input from context, I am using a small {
Moving: {
invoke: {
src: 'moveItem',
input: fromContext('item', 'strategy'),
onDone: { target: 'Run', actions: 'clearItem' },
onError: 'Recovering',
},
},
}
export function fromContext<T extends object, K extends keyof T>(...keys: K[]) {
return ({ context }: { context: T }) => assertPick(context, keys)
}
export function assertPick<T extends object, K extends keyof T>(obj: T, keys: K[]): Required<Pick<T, K>> {
const result = pick(obj, keys) as T & Required<Pick<T, K>>
return assertKeys(result, keys)
}
export function assertKeys<T extends object, K extends keyof T>(obj: T, keys: K[]): T & Required<Pick<T, K>> {
for (const key of keys) {
if (obj[key] === undefined)
throw new Error(`Missing key '${String(key)}', expected [${keys}], found [${Object.keys(shake(obj))}]`)
}
return obj as T & Required<Pick<T, K>>
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
In v4 it was possible to narrow down context type by state - how does one do this in v5?
https://xstate.js.org/docs/guides/typescript.html#typestates
Beta Was this translation helpful? Give feedback.
All reactions