Home > Net >  Strict type argument when calling generic function
Strict type argument when calling generic function

Time:11-20

Suppose I have this generic function definition:

function example<T>(...args): Partial<T> {
    ...
}

The question is how to force the user of this function to insert type argument when calling this function. For example:

example(...inputArgs);       // compilation error without using specific type.
example<User>(...inputArgs); // no compilation error when using specific type.

CodePudding user response:

You can achieve something like this by giving the type parameter a default, and then making the type of args conditional, so that when T is unspecified, args has an impossible type.

I've written any[] here for the type of args when T isn't never; you should replace this with whatever more specific type the rest parameter should have in your application.

function example<T = never>(...args: [T] extends [never] ? [never] : any[]): Partial<T> {
    return {};
}

// error as expected
const test: object = example();
// OK
const test2: object = example<object>();

Playground Link

If you want the error message to be more informative, you can use this trick:

function example<T = never>(...args: [T] extends [never] ? [never, 'You must specify the type parameter explicitly'] : any[]): Partial<T> {
    return {};
}

Playground Link

  • Related