I am trying to automatically infer function argument types as follows:
const FUNCTION_A = "a";
const FUNCTION_B = "b";
type FunctionKeyType = typeof FUNCTION_A | typeof FUNCTION_B;
function functionA(arg: string): string {
return "A";
}
function functionB(arg: number): string {
return "B";
}
type AnyFunctionType = (arg: any) => string;
const funcs: Record<FunctionKeyType, AnyFunctionType> = {
[FUNCTION_A]: functionA,
[FUNCTION_B]: functionB
}
console.log("A:", funcs[FUNCTION_A]("a")) // works
console.log("B:", funcs[FUNCTION_B](0)) // works
console.log("B:", funcs[FUNCTION_B]("fail")) // should fail typechecking but does not
- There will be a large number of
functionswith uniqueargtypes, but each will always have a single argument calledargand return astring - I need to have a mechanism for
key=>function, however it doesn't necessarily need to be aRecord
Is there a way to write AnyFunctionType such that when I use a function via funcs["..."], it infers the type of the argument?
funcs["a"]("a")? Or will the key be a plain string?