Had trouble for searching for information on this because every search for "get actual type typescript" was about runtime type checks.
I have an object with various keys set to functions. I would like to make a dependent type on that object which is a record of those keys to the return values of those functions.
Example:
const myFunctions = {
story: StoryBuilder,
form: FormBuilder
};
type FunctionResults = {
[K in keyof typeof myFunctions]: ReturnType<typeof myFunctions[K]>;
};
const results: FunctionResults = ...;
This works great. I get typechecking for keys story and form that must be the return values of the respective functions in myFunctions. However, now let's say I want to do some type verifiction on myFunctions. I want to ensure all its keys are functions that take two integers and return something (they each return something different). I could make a type like this:
type FunctionHolder = Record<string, (a: number, b: number) => unknown>;
// Apply to myFunctions for type checking
const myFunctions: FunctionHolder {
// same as above
};
Okay, now I can make sure myFunctions has the correct values in its keys. Except now, typeof myFunctions[K] in the FunctionResults type definition is returning unknown instead of the actual, concrete type of the key in the variable. I get why: I've told typescript this object has values which return unknown and, if it wasn't a constant value, it could change at any time. Given that it is constant however, is there some way to ask "what is the actual type of the constant value"? My goal is to have proper type checking on myFunctions.
I guess I could key myFunctions implicitly typed and assign it to a throwaway const of the proper type right below it to get the type errors, but it'd be nicer if I could have the error at assignment. Also because, in my real code, the type of myFunctions is a Partial dictating what key values are allowed and then I get the appropriate intellisense in VSCode as I'm adding keys to myFunctions.