Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strict type argument when calling generic function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading