typescript - 根据 bool 参数使用条件返回类型

标签 typescript

我正在编写一个库,我想提供更准确的类型,这样库用户就不会在我下面的示例中选择错误的类型。

如果参数 convertJSONOutput 设置为 true,此方法返回 IPlayerStatsIStatsItem[]

public async getStatsById(
    userId: string,
    timeWindow: TimeWindow = TimeWindow.Alltime,
    convertJSONOutput: boolean = true
  ): Promise<IPlayerStats | IStatsItem[]> {
  // Ommitted
}

问题:

我可以指定一个条件返回类型来指示将返回什么接口(interface)(取决于 convertJSONOutput bool 参数)吗?

最佳答案

基于 bool 参数返回不同类型的最简单方法是重载:

function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: true): Promise<IPlayerStats>;
function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: false): Promise<IStatsItem[]>;
function getStatsById(
    userId: string,
    timeWindow: TimeWindow = TimeWindow.Alltime,
    convertJSONOutput: boolean = true
  ): Promise<IPlayerStats | IStatsItem[]> {

当您调用它时,会根据参数的值推断出缩小的类型:

// Promise<IPlayerStats>
const a = getStatsById('', undefined, true);

// Promise<IStatsItem[]>
const b = getStatsById('', undefined, false);

重要的部分是每个重载都指定了确切的字面值 truefalse,而不是 boolean 类型。然后返回类型与此相关联。我在下面强调了这种关系。

//                              **** =>        ************
getStatsById(convertJSONOutput: true): Promise<IPlayerStats>;

我稍微调整了代码以便创建一个独立的示例,它假定 TimeWindowIStatsItemIPlayerStats 已经存在定义:

function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: true): Promise<IPlayerStats>;
function getStatsById(userId: string, timeWindow: TimeWindow, convertJSONOutput: false): Promise<IStatsItem[]>;
function getStatsById(
    userId: string,
    timeWindow: TimeWindow = TimeWindow.Alltime,
    convertJSONOutput: boolean = true
  ): Promise<IPlayerStats | IStatsItem[]> {
  // Ommitted
}

// Promise<IPlayerStats>
const a = getStatsById('', undefined, true);

// Promise<IStatsItem[]>
const b = getStatsById('', undefined, false);

关于typescript - 根据 bool 参数使用条件返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801536/

相关文章:

typescript - 在 nestjs 中使用类验证器验证环境变量?

node.js - 如何使用 TypeScript 将输入 JSON 对象转换为 Node.JS 中的模型类?

css - 如何在 Angular 中进行无限翻转?

angular - 为什么大多数 Angular UI 组件不使用对象来配置输入?

javascript - 在单行中声明多个变量 + Angular 2 和 TypeScript

javascript - Typescript 从嵌套在数组中的数组中拼接项目

typescript - 如何编写一个函数,通过类型检查将字段添加到对象数组中?

reactjs - 带按钮或 anchor 类型的转发引用 - typescript

javascript - => Angularjs。对于传入的值,我是否正确理解了这一点?

typescript - "Module not found"扩展类时