使打字稿函数返回类型以输入为条件

sev*_*sev 2 typescript typescript-generics

在下面的代码中,即使我们将其用作函数的输入,也将始终分配 ab类型。有没有一种方法可以实现一些智能打字稿魔法,例如使用泛型,以便根据函数输入分配正确的类型?number | stringbstringFormat.hexb

enum Format{
  hex,
  integer
}

function fun (a: Format){
  const k = Math.floor(Math.random()*100)
  if (a === Format.hex) {
    return k.toString(16)
  }
  else { 
    return k
  }
}

const b = fun(Format.hex)
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用重载函数签名,如下所示:

enum Format {
  hex,
  integer
}

// Overload signature without a body.
// Here you're saying that if the function gets called with Format.hex it will return string 
function fun(a: Format.hex): string;
function fun(a: Format.integer): number;
function fun(a: Format) {
  const k = Math.floor(Math.random() * 100);

  if (a === Format.hex) {
    return k.toString(16);
  }

  return k;
}

const b = fun(Format.hex); // b is now of type 'string'
Run Code Online (Sandbox Code Playgroud)