Home > Back-end >  Is 'false' a valid return type in TypeScript?
Is 'false' a valid return type in TypeScript?

Time:10-14

Let's say I have a function that always returns false:

function alwaysReturnsFalse(): boolean {
  // some code
  return false;
}

I'd like to make that clear by using false instead of boolean:

function alwaysReturnsFalse(): false {
  // some code
  return false;
}

TypeScript seems to accept this when I try it, but is that bad practice? I couldn't find any examples, or anything in the TypeScript documentation about it, so I'm guessing I probably shouldn't do it. I've never heard of false being a type. But, I think it would make the code a lot more understandable at a glance, especially for a more complex function that returns say, a Promise or false.

Thank you!

CodePudding user response:

Yes, you can define the return type of a function in TS as a single primitive value. This is kind of a trivial example, but the basic functionality of constraining variables to specific, finite sets of values allows you to carefully control the expectations of a piece of functionality. This is an approach that is simpler and easier-to-use than enums, so it's good to be familiar with.

A multiple-value example sheds more light:

type chalkColor = "red" | "yellow" | "green" | "blue" ;

const getRandomColor = (): chalkColor => {
  //Just returns a random color.
  //You are assured it's one of only 4 possible values.
}

CodePudding user response:

TypeScript seems to accept this when I try it, but is that bad practice? - No, there is nothing wrong in passing the primitive value false as a return type but I am just thinking is the function still required if it is always going to return false.

Can not we directly use false instead of calling this function ?

function alwaysReturnsFalse(): false {
  return false;
}

const res = alwaysReturnsFalse();

OR

const res = false;

Which solution will you prefer ? I think second one right as it is more compatible/less code.

  • Related