Here's a function I've been working on:
type Action = 'doX' | 'doY'
function canIPerform(actions: Action[]) : {[action: string]: Boolean} {
// Some business logic
return {'doX': true}
}
My goal is to type it in a way that ensures the returned map only includes keys that were passed in the argument:
let x = canIPerform(['doX'])
// x should be typed as {[k in 'doX']: boolean}
let x = canIPerform(['doY', 'doX'])
// x should be typed as {[k in 'doX' | 'doY']: boolean}
The challenge lies in the fact that arrays are evaluated at runtime, but I've found a workaround by utilizing const
:
let x = canIPerform(['doX', 'doY'] as const)
I have attempted various approaches to enforce this behavior, but haven't discovered an equivalent of keyof
that functions effectively for tuples.