函数具有泛型类型参数.

当上下文为空时,我想输入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"});

推荐答案

你可以用Function Overloads来做到这一点.

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.

TypeScript Playground

Typescript相关问答推荐

使用新控制流的FormArray内部的Angular FormGroup

APP_INITIALIZER—TypeError:appInits不是函数

如何用不同的键值初始化角react 形式

在TypeScript中使用泛型的灵活返回值类型

属性的类型,该属性是类的键,其值是所需类型

了解类型规则中的关键字

跟踪深度路径时按条件提取嵌套类型

Typescript 中相同类型的不同结果

接受字符串或数字的排序函数

作为函数参数的联合类型的键

如何为带有参数的函数类型指定类型保护?

有没有一种方法可以提升对象的泛型级别,而对象的值是泛型函数?

我的类型谓词函数不能像我预期的那样工作.需要帮助了解原因

我如何键入它,以便具有字符串或数字构造函数的数组可以作为字符串或数字键入s或n

T的typeof键的Typescript定义

使用NextJS中间件重定向,特定页面除外

在类型{}上找不到带有string类型参数的索引签名 - TypeScript

带有过滤键的 Typescript 映射类型

为什么 TypeScript 类型条件会影响其分支的结果?

React router - 如何处理嵌套路由?