I have the following function:
async function get<U>(url: string): Promise<U> { return getUrl<u>(url); }
However, it is possible to call it like this (U is set to any by TS):
get('/user-url');
Is there a way to define this function such that it requires U to be provided explicitly, as in
get<User>('/user-url');
Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.
The TypeScript documentation explains Generics as “being able to create a component that can work over a variety of types rather than a single one.” Great! That gives us a basic idea. We are going to use Generics to create some kind of reusable component that can work for a variety of types.
TypeScript supports generic classes. The generic type parameter is specified in angle brackets after the name of the class. A generic class can have generic fields (member variables) or methods.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With