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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…