The never type

TypeScript 2.0 introduces a new primitive type never.The never type represents the type of values that never occur.Specifically, never is the return type for functions that never return and never is the type of variables under type guards that are never true.

The never type has the following characteristics:

  • never is a subtype of and assignable to every type.
  • No type is a subtype of or assignable to never (except never itself).
  • In a function expression or arrow function with no return type annotation, if the function has no return statements, or only return statements with expressions of type never, and if the end point of the function is not reachable (as determined by control flow analysis), the inferred return type for the function is never.
  • In a function with an explicit never return type annotation, all return statements (if any) must have expressions of type never and the end point of the function must not be reachable.Because never is a subtype of every type, it is always omitted from union types and it is ignored in function return type inference as long as there are other types being returned.

Some examples of functions returning never:

  1. // Function returning never must have unreachable end point
  2. function error(message: string): never {
  3. throw new Error(message);
  4. }
  5. // Inferred return type is never
  6. function fail() {
  7. return error("Something failed");
  8. }
  9. // Function returning never must have unreachable end point
  10. function infiniteLoop(): never {
  11. while (true) {
  12. }
  13. }

Some examples of use of functions returning never:

  1. // Inferred return type is number
  2. function move1(direction: "up" | "down") {
  3. switch (direction) {
  4. case "up":
  5. return 1;
  6. case "down":
  7. return -1;
  8. }
  9. return error("Should never get here");
  10. }
  11. // Inferred return type is number
  12. function move2(direction: "up" | "down") {
  13. return direction === "up" ? 1 :
  14. direction === "down" ? -1 :
  15. error("Should never get here");
  16. }
  17. // Inferred return type is T
  18. function check<T>(x: T | undefined) {
  19. return x || error("Undefined value");
  20. }

Because never is assignable to every type, a function returning never can be used when a callback returning a more specific type is required:

  1. function test(cb: () => string) {
  2. let s = cb();
  3. return s;
  4. }
  5. test(() => "hello");
  6. test(() => fail());
  7. test(() => { throw new Error(); })