To create a type object that acts as an alias for the type arguments provided to a templated function, you can use a conditional type setup in TypeScript. This type object will resolve to 'undefined' if incorrect generic types are supplied when defining the type alias.
type VerboseTypeParams<T,U,V> = V extends T? {"T":T, "U":U, "V":V}: undefined;
type concrete = VerboseTypeParams<string,number, string>; // Result corresponds to the desired type
Subsequently, you can extract individual types from this type alias object within a wrapper function.
// Wrapper function with generics
function verboseGenericFunc(thing: concrete["T"] ):concrete["V"] {
return verboseGenericFuncVue<concrete["T"],concrete["U"],concrete["V"]>(thing);
};
The purpose of this wrapper function is to call the actual target function while abstracting away the need to provide any type arguments explicitly. TypeScript will flag errors if incompatible wrappers are created or incorrect types are passed to the corresponding wrapper functions.
// Function with multiple type parameters (e.g., from Vue)
function verboseGenericFuncVue<T, U, V extends T>(thing: T): V {
// Perform operations involving T, U, V
return thing as V;
};
type concreteBad = VerboseTypeParams<string,number, number>; // Resolves to 'undefined'
// Incorrect Generic function wrapper triggering TypeScript error due to key lookup issues with 'concreteBad' being undefined
function verboseGenericFuncBad(thing: concreteBad["T"] ):concreteBad["V"] {
return verboseGenericFuncVue<concreteBad["T"],concreteBad["U"],concreteBad["V"]>(thing);
};
const v1 = verboseGenericFunc("1"); // Successful call to wrapped function without specifying types
const v2 = verboseGenericFunc(1); // Type error raised by TypeScript since a string was expected according to 'concrete'
Playground Link