One of the functions in my code has a generic type argument.
In certain cases, when the context is void, I need to input 0 arguments; otherwise, I need to input 1 argument.
If I define the function argument as context: Context | void
, I can still add void type even when I should include a context.
Is there a way for me to specify that 0 arguments are expected or check if it is typed as void?
class TestClass<Context = void> {
protected context : Context
constructor(context: Context) {
this.context = context;
}
}
export function genericVoidNeedArgument<Context = void>(
context: Context,
) {
// Can we check the type somehow?
return new TestClass(context);
}
type UserType = {
id: string
// and so on..
};
// Expected output: No, Actual output: Error
// An argument for 'context' was not provided.
genericVoidNeedArgument();
// Expected output: Error, Actual output: Error
genericVoidNeedArgument<UserType>();
// Expected output: Yes, Actual output: Yes
genericVoidNeedArgument<UserType>({id: "123"});