I’m making a package that lets you define “actions” and then “trigger” them. Actions are functions that take some payload and a callback to trigger more actions recursively.
Ideally, using the package would look like:
import { ActionDef, getTrigger } from 'thePackage'
// 1. Define some actions.
//
// We define the type of their payload and what they do.
const action1 = ((payload, trigger) => {
console.log('action1', payload)
trigger('action2', {y: 'abc'})
}) satisfies ActionDef<MyActions, {x: number}>;
const action2 = ((payload, trigger) => {
console.log('action2', payload)
trigger('action1', {x: 123})
// trigger('action1', {x: '123'}) <- Should error, wrong payload type
// trigger('action3') <- Should error, unknown action name
}) satisfies ActionDef<MyActions, {y: string}>;
const actions = {
action1,
action2
}
type MyActions = typeof actions;
// 2. Trigger some of our actions.
//
// Elsewhere in the code, we "trigger" these actions.
// The package decides what this actually means: it gives us the `trigger` function.
const trigger = getTrigger(actions);
function triggerSomeActions() {
trigger('action1', {x: 123});
trigger('action1', {x: 234});
trigger('action2', {y: 'abc'});
// These should produce a typescript error:
// trigger('action1', {x: '123'}) <- Wrong payload type
// trigger('action3') <- Unknown action name
}
I want typescript to validate that the calls to trigger
(both from getTrigger
and as callbacks) are valid (valid name and valid corresponding payload).
Now this doesn’t work because of the circular type reference of MyActions
.
I’m wondering if there is a way to type this properly, without making it too annoying for the developer using the package.
So far these are the types I have in the package:
type ActionDef<A extends Actions, P> = (payload: P, triggerCallback: TriggerFunc<A>) => void
type Actions = Record<string, ActionDef<any, any>>;
type ActionName<A extends Actions> = keyof A;
type ActionPayload<
A extends Actions,
K extends keyof A
> = A[K];
type TriggerFunc<
A extends Actions,
> = (<K extends ActionName<A>>(actionName: K, payload: ActionPayload<A, K>) => void);
// Get a function to trigger our actions. The content of this could change.
function getTrigger<A extends Actions>(actions: A): TriggerFunc<A> {
const cb: TriggerFunc<A> = (actionName, payload) => {
console.log('cb was called', actionName)
actions[actionName](payload, cb)
}
const trigger: TriggerFunc<A> = (actionName, payload) => {
console.log('triggered', actionName)
actions[actionName](payload, cb)
}
return trigger;
}
export { ActionDef, getTrigger }
One solution to get rid of the circular type reference would be to separately list the action names and payload types, in something like:
type ActionTypes = {
action1: {x: number};
action2: {y: string};
}
and then use this instead of MyActions
when defining the action functions, but it hurts the DevX.