When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible.
For instance, if all functions are required to return a string:
type myFuncsType = (...args: any) => string
Each function should adhere to this type constraint. However, when a function always returns a constant string:
const myFunc1 = () => "MyString" as const
// The inferred type is:
const myVal = myFunc1()
// typeof myVal = "MyString"
We specified that our functions should extend a predefined known type (myFuncsType
), yet when assigning this type to the function, the general type takes precedence over the inferred accurate type - something I wish to avoid:
const myFunc1: myFuncsType = () => "MyString" as const
const myVal = myFunc1()
// typeof myVal = string
I attempted to solve this issue using generics, but they require specifying a predefined type and do not account for the return type during declaration.
How can I enforce the restriction of the return type to extend a predefined type while still returning the exact inferred return type from the declaration?