TypeScript需要提供通用参数 [英] TypeScript require generic parameter to be provided
问题描述
我具有以下功能:
async function get<U>(url: string): Promise<U> {
return getUrl<u>(url);
}
但是,可以这样称呼它(TS将U设置为any):
However, it is possible to call it like this (U is set to any by TS):
get('/user-url');
有没有一种方法可以定义此函数,使得它需要显式提供U,如
Is there a way to define this function such that it requires U to be provided explicitly, as in
get<User>('/user-url');
推荐答案
对此没有内置支持,但是我们可以设计一个方案,其中不传入类型参数将使用默认的泛型类型参数生成错误.和条件类型.即,我们将给 U
一个默认值 void
.如果默认值是 U
的实际值,那么我们将在函数中键入参数,而该参数实际上不应传递给它,以获取错误:
There is no built-in support for this, we can however engineer a scenario where not passing in a type parameter will generate an error, using default generic type arguments and conditional types. Namely we will give U
a default value of void
. If the default value is the actual value of U
, then we will type the parameter to the function as something that should not really be passed in so as to get an error:
async function get<U = void>(url: string & (U extends void ? "You must provide a type parameter" : string)): Promise<U> {
return null as any;
}
get('/user-url'); // Error Argument of type '"/user-url"' is not assignable to parameter of type '"You must provide a type parameter"'.
class User {}
get<User>('/user-url');
错误消息不是理想的,但是我认为它将使消息得到传播.
The error message is not ideal, but I think it will get the message across.
Edit: For a solution where the type parameter is used in parameter types see here
这篇关于TypeScript需要提供通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!