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

如何根据Typescript中参数的类型声明返回类型

  •  1
  • feerlay  · 技术社区  · 4 年前

    我想根据参数的类型推断返回类型。

    这是我的尝试

    type Arg = string | (() => string)
    
    function fn1(arg: Arg): typeof arg extends Function ? () => string : string {
      if (typeof arg === "function") {
        return () => arg();
      }
    
      return arg;
    }
    
    const a = fn1("hello") // a should be "string"
    const b = fn1(() => "hello") // b should be () => "string"
    
    

    Link to demo

    不幸的是,我不知道为什么typescript在线失败 return () => arg() 有一个错误 Type '() => string' is not assignable to type 'string' 其中此行位于if语句中。

    1 回复  |  直到 4 年前
        1
  •  2
  •   yqlim    4 年前

    使用 function overloads :

    function fn1(arg: string): string;
    function fn1(arg: () => string): () => string;
    function fn1(arg: string | (() => string)){
      if (typeof arg === 'function'){
        return () => arg();
      }
      return arg;
    }
    
    const a = fn1("hello");
    const b = fn1(() => "hello");
    

    Link to demo .