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>({ ...})
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.
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