A function has generic type argument.
When context is void, I want to input 0 arguments, otherwise I want to input 1 argument.
If I used as context: Context | void in function argument, Even when I need to add context, But I can add void type.
is there any way to input 0 argument or check whether 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 check type..?
return new TestClass(context);
}
type UserType = {
id: string
// and so on..
};
// expected : o, real : error
// An argument for 'context' was not provided.
genericVoidNeedArgument();
// expected : error, real : error
genericVoidNeedArgument<UserType>();
// expected : o, real : o
genericVoidNeedArgument<UserType>({id: "123"});
>Solution :
You can use Function Overloads to do that.
class TestClass<Context = void> {
protected context: Context;
constructor(context: Context) {
this.context = context;
}
}
function genericVoidNeedArgument(): TestClass<void>;
function genericVoidNeedArgument<Context>(
context: Context
): TestClass<Context>;
function genericVoidNeedArgument(context?: any): any {
return new TestClass(context);
}
type UserType = {
id: string;
};
genericVoidNeedArgument();
genericVoidNeedArgument<UserType>({id: "123"});
genericVoidNeedArgument<UserType>();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -> Expected 1 arguments, but got 0.