代码之家  ›  专栏  ›  技术社区  ›  kentor

根据布尔参数使用条件返回类型

  •  1
  • kentor  · 技术社区  · 8 年前

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

    此方法要么返回 IPlayerStats IStatsItem[] 如果参数 convertJSONOutput

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

    问题是:

    转换器输出

    1 回复  |  直到 8 年前
        1
  •  5
  •   Fenton    7 年前

    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);
    

    true 或 false boolean

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

    我已经稍微修改了代码,这样我就可以创建一个独立的示例 TimeWindow IStatsItem ,和 IPlayerStats

    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);
    
    推荐文章