Typescript: Code section below a `never` expression should be marked as unreachable

Created on 5 Dec 2018  路  4Comments  路  Source: microsoft/TypeScript

Suggestion

According to the TypeScript handbook:

The never type represents the type of values that never occur. For instance, never is the return type for a function expression or an arrow function expression _that always throws an exception or one that never returns;_ Variables also acquire the type never when narrowed by any type guards that can never be true.

Which means that function or expression that "returns" never either terminates the program prematurely or never return (i.e. infinite loop), this leads to the section of code below it never get to execute.

Examples

console.log('before') // reachable
process.exit(0) // this function returns `never` in @types/node 10.12.0
console.log('after') // should be marked as unreachable

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.

Related issues

https://github.com/Microsoft/TypeScript/issues/12825

Experience Enhancement

Most helpful comment

I have a lint rule that forces you to write return process.exit(0) instead, which is then picked up by control flow analysis and subsequent statements are marked as unreachable: https://github.com/fimbullinter/wotan/blob/master/packages/mimir/docs/return-never-call.md

The CLI documentation contains a quick start guide: https://github.com/fimbullinter/wotan/blob/master/packages/wotan/README.md

All 4 comments

Limited by the same issue here: #8655

Specifically, see this comment here.

Reachability in your example is determined by type, but the graph is built syntactically.

I have a lint rule that forces you to write return process.exit(0) instead, which is then picked up by control flow analysis and subsequent statements are marked as unreachable: https://github.com/fimbullinter/wotan/blob/master/packages/mimir/docs/return-never-call.md

The CLI documentation contains a quick start guide: https://github.com/fimbullinter/wotan/blob/master/packages/wotan/README.md

This seems to be implemented, so the Design Limitation tag can be removed @weswigham.

Added in 3.7.

Was this page helpful?
0 / 5 - 0 ratings