如何根据区别因子缩小返回类型

huangapple go评论66阅读模式
英文:

How to narrow down return types based on discriminants

问题

以下是翻译好的部分:

假设我有一个带有参数的函数,该参数只能有两个值 type Value = "a" | "b"。现在我有一个函数,根据该参数的值,应返回不同的结果:

type Value = "a" | "b";

function Method(value: Value){
  if(value === "a") return 1000;
  else return "word";
}

const Result = Method("a");

理论上,如果我的值是 "a"(可以在使用常量值 "a" 调用函数时推断出),我将得到一个数字。如果值为 "b",我期望得到一个字符串。

这段代码中有什么问题,我应该如何使其工作?

英文:

Say I have a function with an argument that can take only two values type Value = "a" | "b". I now have a function which based on the value of that argument, should return a different result:


type Value = "a" | "b";

function Method(value: Value){
  if(value === "a") return 1000;
  else return "word"
}

const Result = Method("a");

In theory, if my value is "a" (which could be inferred when calling the function with a constant value of "a") I would get back a number. If the value is "b", I'd expect a string.

What is wrong in this snippet and how could I make this work?

答案1

得分: 2

你可以按照以下方式使用函数重载

type Value = "a" | "b";

function Method(value: "a"): number;
function Method(value: "b"): string;
function Method(value: Value) {
  if (value === "a") return 1000;
  else return "word";
}

const Result = Method("a");
英文:

You can use function overloads as below:

type Value = "a" | "b";

function Method(value: "a"): number;
function Method(value: "b"): string;
function Method(value: Value){
  if(value === "a") return 1000;
  else return "word";
}

const Result = Method("a");

答案2

得分: -1

可以使用switch语句代替if语句,只处理这两个值:

switch (value) {
  case 'a':
    return 1000;
  case 'b':
    return 'word';
}
return null; // 在值不符合预期情况下返回null,但这是可选的
英文:

You can use a switch statement instead of an if and only acct in this 2 values:

switch (value) {
  case 'a':
    return 1000;
  case 'b':
    return 'word'
}
return null; //in case the value falls out the expected values but this is optional

huangapple
  • 本文由 发表于 2023年2月10日 02:52:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定