razgraf
razgraf

Reputation: 221

How to narrow down return types based on discriminants

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?

Upvotes: 0

Views: 71

Answers (2)

Shiin Zu
Shiin Zu

Reputation: 166

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

Upvotes: -1

Kavian Rabbani
Kavian Rabbani

Reputation: 984

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");

Upvotes: 2

Related Questions