Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent inferring generic type arguments with TypeScript?

I have an API/function that is intended to be used only with generic type arguments (it enforces the shape of an argument based on a generic parameter). I want to prevent calling the API without a generic parameter (thus inferring the type from the arguments), because it defeats the purpose of my function and will be confusing to users of the API. I would rather the compiler just enforce that a generic type argument is always required. For example:

function foo<T>(arg: Config<T>) { ... } 

How can I ensure the type argument T is always specified by the caller? i.e. foo<Bar>({ ...})

like image 355
Craig Smitham Avatar asked Nov 07 '22 20:11

Craig Smitham


1 Answers

It doesn't appears to be a functionality yet. That is all that the docs says on generics and inference:

function identity<T>(arg: T): T { return arg; }
let output = identity<string>("myString");  // type of output will be 'string'
let output = identity("myString");  // type of output will be 'string'

Notice that we didn’t have to explicitly pass the type in the angle brackets (<>); the compiler just looked at the value "myString", and set T to its type.

And that's basically it... No hint on how to write it so that identity("myString") throws an error but identity<string>("myString") doesn't.

like image 111
Nino Filiu Avatar answered Nov 15 '22 10:11

Nino Filiu