英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论