Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript require generic parameter to be provided

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'); 
like image 690
Kizer Avatar asked Jul 04 '18 12:07

Kizer


People also ask

How do you pass a generic type as parameter TypeScript?

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.

Why do we need generics in TypeScript?

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.

How do generics work in TypeScript?

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.

Does TypeScript support generics?

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.


1 Answers

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

like image 97
Titian Cernicova-Dragomir Avatar answered Sep 19 '22 22:09

Titian Cernicova-Dragomir