Unexpected absence of error when inferring `never` return type from unidentified function

What causes the discrepancy in outcomes when inferring the never return type in the following TypeScript code (Version 4.3.2 or 4.4.0-nightly)? See comments in the code snippet below:

const willThrowException: (message: string) => never = (message) => {
    throw new Error(message);
}

try {
    willThrowException('some message');
    willThrowException('another message'); // OK: compiler will error 'Unreachable code detected'
} catch(e) {}

const willThrowExceptionToo = (message: string): never => {
    throw new Error(message);
}

try {
    willThrowExceptionToo('some message');
    willThrowExceptionToo('another message'); // NOT OK: compiler will not error
} catch(e) {}

The autocomplete feature in the TypeScript compiler recognizes that the function has a return type of never:

https://i.sstatic.net/mfXFB.png

However, the execution flow is not blocked in the same way as indicated by the declared type, which is more explicit but aligns better with best practices.

Answer №1

The TypeScript compiler has a limitation where it performs code path analysis before type inference, leading to issues like the second example not working even though it is strongly typed but not explicitly typed.

While it would be beneficial for this limitation to be better documented, you can refer to this pull request for more information.

If you dislike providing a type annotation as in the first example, another approach is to create an overload that statically defines the throw condition.

function willThrowException (message: string): never;
function willThrowException (message: string) {
    throw new Error(message);
}

It's interesting how the overload is explicit while the return type isn't, sparking a potential discussion on TypeScript's Discord or GitHub issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Persuade TypeScript to trust that all necessary keys will be present in an object

I find myself in this particular scenario: const user: UserObj = User.get(userId); if ([user.foo, user.bar, user.baz].some((k) => !k)) throw new Error(`Missing fields for user ${userId}`); const createParams: CreateParams = { firstName: user.first ...

What are the steps for compiling TypeScript using Babel 7 CLI?

Here's the issue: When I run 'babel ./src/MyTypescript.ts --out-dir ./wwwroot/js/', I don't get any errors and it just says '0 compiled'. Even though my .babelrc file contains all the necessary configurations for Babel 7 to ...

A step-by-step guide on setting up a database connection with .env in typeorm

I encountered an issue while attempting to establish a connection with the database using ormconfig.js and configuring .env files. The error message I received was: Error: connect ECONNREFUSED 127.0.0.1:3000 at TCPConnectWrap.afterConnect [as oncomplete] ( ...

What is the method for utilizing an array of strings as keys for an interface?

Imagine I have an array of strings like this: const items = ['item1','item2','item3','item4', ...] Is it possible to create a custom interface using the values from items in this manner: interface Items { item1: b ...

Error: The usage of document is invalid in this context (Typescript)

Whenever I attempt to utilize TypeScript, the error message "ReferenceError: document is not defined" keeps popping up while using document.getElementByID();. Can someone please advise on how to resolve this issue? ...

The declaration file for the 'vimeo' module was not located

My current setup includes typescript v^3.4.2, in an express app (^4.14.1), using node v11.3.0. During the build process for typescript, I encountered this error: Could not find a declaration file for module 'vimeo'. '/Users/me/Code/MyServe ...

What is the reason for the error message stating that "'VideoSource' is being used as a value here despite it only referring to a type?"

When I run the first if check, everything works fine without any errors. However, when I move to the else block, an error is thrown. The error message reads: 'VideoSource' only refers to a type, but is being used as a value here. let element ...

What causes the exception in JavaScript to be an empty object?

try { let temporary = null; temporary.split(','); } catch (error) { Logger().info('caught error: ', error, error.constructor); } output: caught error: {} undefined I attempted to use JSON.stringify and encountered the sa ...

Transformation of Python code into Blockly blocks

As the founder of edublocks.org, I am interested in adding Python to Blocks functionality on the platform. At the moment, users can only transition from Blocks to Python. Is there anyone who has experience with this and can provide guidance on how to achi ...

What is the best approach to handling an undefined quantity of input FormControls within Angular?

I have a unique task in my Angular application where I need to collect an unspecified number of entries, such as names, into a list. My goal is to convert this list of names into an array. To facilitate this process, I would like to offer users the abilit ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

Step-by-step guide for deploying an Angular 2 CLI app on GitHub

As a front-end engineer, I have limited experience with deployment. Currently, I am working on my pet project using angular-cli. What is the best way to deploy it on GitHub Pages? Are there any other straightforward methods for deployment? ...

Tips on showcasing Java map information obtained from the backend on an Angular/Typescript interface

I have a 'detailsMap : any' variable from the backend that contains multiple rows in the format (key1,key2). I need to display this data in the UI using TypeScript/Angular2. Please advise on how I can achieve this. key1 : { Name:'ABC' , ...

Exploring the Power of Angular 5 with TypeScript and ES2015 Syntax

I have been working on an angular 5 application where I needed to incorporate the dmn-js library. Unfortunately, this library does not come with typings available. To tackle this issue, I followed the guidelines provided in the Angular-CLI wiki regarding h ...

Ways to incorporate the use of the useAsync hook within a submit function

After importing useAsync(hook from 'react-async') and attempting to utilize it post form submission for a POST request, a "can't use hooks inside functions" error is encountered due to the rules of hooks. How can this issue be resolved in o ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

Even after setting a new value to a variable in Vue, it may still reference the old

init(){ this.unsortedList = this.selectedVoucher.approvalStepList; // list in original order this.sortedList = this.unsortedList .sort(function(a,b){ if (new Date(a.createDate) < new Date(b.createDate)) return -1; ...

Is there a way for me to transfer a file from my personal computer?

I am trying to use Selenium with JavaScript, but I am having trouble uploading files from my local machine. I attempted to use 'upload.sendKeys(file path)', but it doesn't seem to be working. When I click on the upload button and a window op ...

React application facing a problem with bracket notation in Typescript

After creating a form state to store and update input changes, I encountered an issue: const [form, setForm] = useState({ user: '', email: '', password: '', }); I then wrote a function to handle form changes: const handle ...