I have a createDispatcher
function that accepts a record of functions.
It will return a dispatch
function that expects a record with a key corresponding to a key in the record fed to createDispatcher
before.
Kinda hard to explain, but have a look at the examples below, I think it should become obvious.
const funcs = {
upCase: (s: string) => s.toUpperCase(),
double: (n: number) => 2*n,
}
const dispatch = createDispatcher(funcs) // TBD
dispatch({upCase: "test"}) // OK: TEST
dispatch({double: 42}) // OK: 84
dispatch({double: "test"}) // should be compile error
dispatch({foo: 0}) // should be compile error
dispatch({upCase: "test", double: 42}) // should be compile error, exactly one key expected
dispatch({}) // should be compile error, exactly one key expected
Below is my current implementation of createDispatcher
.
function createDispatcher(funcRecord: Record<string, (input: any) => any>) {
function dispatch(inputRecord: Record<string, any>) {
for (const i in inputRecord) {
const func = funcRecord[i]
if (func !== undefined)
return func(inputRecord[i])
}
}
return dispatch
}
It works, but it's too weakly typed.
All the examples above type-check, whereas I only want 1 and 2 to be allowed.
Can anybody help?