Throwing in a ternary/conditional operator expression in Typescript 2

When attempting to compile the following code:

const value = "20"
const x : string | never = "10" === value ? throw Error("bad things") : "hello"

An error is encountered on throw - expression expected. One way to resolve this issue is by using an inline method invoked in place, although it may not look very clean. (

(() => {throw Error("bad things")})()
)

Why is it not acceptable to use throw in a branch of the ternary operator? Are there alternative syntax options that could work, or perhaps certain compile settings that I am overlooking?

It also seems that throw does not function properly without curly brackets in the function body, as shown in the workaround, (

(() => throw Error("bad things"))()
).

Answer №2

It's an interesting quirk in the syntax of this particular language.

The use of throw ex can be seen as producing a type of never, given that never represents functions that do not return, which accurately describes what happens when you throw. In programming languages with a concept known as a bottom type (which is the technical term for what never signifies - it's more than just a peculiar keyword).

Contrary to statements like for (let x of ...), which clearly do not return any value, throw ex can be interpreted as returning never.

Answer №3

When it comes to constructing languages, there is a distinction between statements and expressions. For example, assigning a value to x is a statement or operation rather than a value or expression.

Attempting something like the following won't work for the same reason:

const x : string | never = "10" === value ? for(var i in myArray) { /* do stuff */ } : "hello".

This goes against the rules of the language, although you may find ways to work around it using self-evaluation functions that theoretically evaluate as an expression.

To understand the difference between statements and expressions better, refer to this question.

In TypeScript, the never keyword is a peculiar type associated with control flow analysis. It prevents treating statements as expressions. If you prefer not to use immediately invoked function expressions, consider using a regular function instead:

const value = "20"
var thrower = () => { throw Error("bad things"); }
const x: string | never = "10" === value ? thrower() : "hello";

If this is truly what you intend to do, the following approach would be more readable:

//...

if(value !== "10")
    throw Error("bad things");

const x: string = "hello";

//...

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

I keep encountering the issue where nothing seems to be accessible

I encountered an error while working on a project using React and Typescript. The error message reads: "export 'useTableProps' (reexported as 'useTableProps') was not found in './useTable' (possible exports: useTable)". It ...

The ts-loader seems to be malfunctioning (It appears that a suitable loader is required to handle this file type, as no loaders are currently set up to process it)

I'm currently in the process of integrating TypeScript into a JavaScript project, but it seems like webpack is not recognizing the ts-loader for files with the .tsx extension. I've attempted to use babel and even tried awesome-ts-loader, but none ...

Experiencing an issue with type error when transitioning syntax from using require to import

After transitioning from require in CommonJS syntax to import in ES Module syntax, I encountered an error. I decided to develop a todo-app using Node.js, TypeScript, and MySQL. To start off, I wrote the initial code snippets below: // db.ts export {}; co ...

Using Ng If with a boolean value to dynamically update the title of a webpage

On my Stock page, I have multiple fields labeled as Title 1. https://i.sstatic.net/FpCsW.png When I run a console.log, it indicates that I am on the first page! ngOnInit() { this.currentPortfolio = this.shrd.getData('currentPortfolio'); ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

Tips for Decreasing Query Time with MatTable and MatTableDataSource

When working with my firestore database, I am trying to query documents and display them while also calculating the total value of a specific column (promiAmount). I have successfully displayed the values in a mat table, but I'm struggling to calcula ...

TypeScript: Error - .map() is an Invalid Function

I have come across numerous questions similar to mine, but the vast majority of them pertain to an Observable, which is not the issue I am facing. The code snippet in question looks like this: selectedItems: Item[] = null; selectedDate: Date = null; subm ...

Cannot compile Angular 4 Material table: Encountering unexpected closing tag

Currently, I am working on an Angular 4 Project that involves using Material. The main task at hand is to implement a table from Angular Material. However, the issue I am facing is that the table does not compile as expected. Here's the HTML code sni ...

What is the process for initiating a Fargate task once a database instance has been successfully provisioned using AWS CDK

I am currently working on an AWS CDK stack that involves creating a Fargate task (using ApplicationLoadBalancedFargateService) from a docker container. The container houses a web application that needs to connect to a database. Upon deploying the CDK stack ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Using Angular with Google Maps: Learn how to retrieve a list of markers from a map and implement onClick events for each one

I am currently using the AGM angular module for Angular 2+ to integrate the Google Map API. In my project, I have a directive that displays waypoints as markers on the map using the Google Map Directions Service. Now, I am looking for a way to handle the ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Utilizing a tuple for indexing in Typescript

Imagine you have a tuple containing keys like ["a", "b", "c"] and a nested object with these keys as properties {a: {b: {c: number}}}. How can you recursively access the members of the tuple as indices in typescript? An example implementation without prop ...

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...

Relying on ModalController within an Angular/Ionic component leads to the error "Unable to resolve all parameters" for the service

I am currently working on a dynamic form module for Ionic 4.7.0 and Angular 5.0.3. The module involves creating a DynamicFormComponent, which internally utilizes the DynamicFormService. This service is designed to operate within the module and does not nee ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...

There was an error during compilation: Module not detected - Unable to locate './xxxx'

Looking for help with importing a file from another folder into my Next.js project. I need assistance with the correct syntax and paths as I am encountering an error. Here is a link to the screenshot of the error: https://i.sstatic.net/jZ6kk.png Below are ...

Opt for ion-select with a range of i to j options

Looking to set up an ion-select menu in Ionic4 where users can pick a value between 20 and 220 without manually typing each number. I attempted to use the approach detailed in this post Tersest way to create an array of integers from 1..20 in JavaScript ...