Given this union type:
type Type = 'one' | 'two' | 'three'
How can I type the following object to ensure that it a) covers every possible value of Type
; and b) allows me to have per-type function signatures?
const factories = {
one(a: string) { return /* whatever */ },
two(a: number, b: number) { return /* whatever */ },
three() { return /* whatever */ }
}
function getFactory<T extends keyof typeof factories>(type: T): typeof factories[T] {
return factories[type]
}
If I don't type the object, like above, I have full type checking but not exhaustivity - I can easily forget or misspell a member. In my real-life use case, Type
is 30+ possibilities and growing so this really matters.
If I use a Record
, such as const factories: Record<Type, any>
or const factories: Record<Type, Function>
, it have exhaustivity but I loose type checking of the function signatures.