简体   繁体   English

调用泛型 function 时的严格类型参数

[英]Strict type argument when calling generic function

Suppose I have this generic function definition:假设我有这个通用的 function 定义:

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.问题是如何在调用此 function 时强制此 function 的用户插入类型参数。 For example:例如:

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

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.您可以通过为类型参数提供默认值,然后使args的类型有条件来实现类似的效果,这样当未指定T时, args具有不可能的类型。

I've written any[] here for the type of args when T isn't never ;T不是never时,我在这里为args的类型写了any[] you should replace this with whatever more specific type the rest parameter should have in your application.您应该将其替换为 rest 参数在您的应用程序中应具有的任何更具体的类型。

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 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM