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

TypeScript:条件类型,并使用布尔参数控制返回类型

  •  3
  • thorn0  · 技术社区  · 8 年前

    function foo(returnString: true): string;
    function foo(returnString: false): number;
    function foo(returnString: boolean) {
      return returnString ? String(Math.random()) : Math.random();
    }
    

    我尝试了下面的代码,但是没有 as any :

    function foo<T extends boolean>(returnString: T): T extends true ? string : number {
      return (returnString ? String(Math.random()) : Math.random()) as any;
    }
    

    我怎样才能摆脱 ?

    错误消息是超级无益的:

    Type 'string | number' is not assignable to type 'T extends true ? string : number'.
      Type 'string' is not assignable to type 'T extends true ? string : number'.
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Jeto    8 年前

    我不太清楚为什么编译器不能按原样接受它(对TypeScript不太熟悉),但下面是您可以做的:

    function foo<T extends boolean>(returnString: T): T extends true ? string : number;
    function foo<T extends boolean>(returnString: T): string | number {
      return returnString ? String(Math.random()) : Math.random();
    }
    

        2
  •  0
  •   zhimin    8 年前

    我认为你应该这样写函数:

    export class MyService {
    
        request(param: false): string; // must a defination;
    
        request(param: true): number;
    
        request(param: any): string | number {
            return null;
        }
    
    }
    

    借自 https://github.com/angular/angular/blob/master/packages/common/http/src/client.ts

    在typescript 2.8中,可以这样编写func:

    function fun<T extends true | false>(t: T): T extends true ? string : number {
        return null;
    }
    
    推荐文章