函数具有泛型类型参数.
当上下文为空时,我想输入0个参数,否则我想输入1个参数.
如果我在函数参数中使用as context: Context | void
,即使我需要添加上下文,But I can add void type.
有没有办法输入0参数或判断它是否被类型化为空?
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"});