Are there inline type assertions in Typescript that function similarly to assertion functions?

Having a good understanding of assertion functions and other inline forms of type assertions in TypeScript, I have two interconnected questions. Firstly, why do they not provide the same level of assertion to TypeScript? Secondly, is there a way to achieve the same effect as an assertion function inline or is there another form of inline assertion that I might be overlooking?

For instance, when conducting runtime validation using typia, my code looks like this:

import typia from "typia";

interface Point {
  x: number;
  y: number;
  tag?: string;
}

function x(v: unknown) {
 assertPoint(v);
 console.log(v.x + v.y);
}

function assertPoint(v: unknown): asserts v is Point {
  typia.assertEquals<Point>(v); // https://typia.io/docs/validators/assert/#assertequals-function
}

The above implementation works smoothly. TypeScript recognizes that `v` conforms to the Point interface after invoking the assertPoint assertion function. However, it fails if I utilize these alternate forms of type assertions:

...
v = <Point> typia.assertEquals<Point>(v); 
v = typia.assertEquals<Point>(v) as Point;

Why does this happen? Aren't they both simply type assertions? Furthermore, is there an inline form of type assertion that behaves like an assertion function, eliminating the need for creating a function for every type I intend to assert at runtime?

Answer №1

An assertion function effectively narrows down its argument as if through control flow analysis. The term "assertion" in this context refers to the runtime aspect of asserting, indicating that we can assume the asserted fact is true if the control flow continues past the assertion (otherwise a runtime exception would occur).

This differs from a type assertion, which only impacts an expression and does not affect anything beyond that.


Currently, there is no direct way to incorporate an inline type assertion that affects control flow analysis. There has been a request for this feature at microsoft/TypeScript#10421, but it is not integrated into the language itself.

It is unlikely that such functionality will be added, as assertion functions essentially fulfill this purpose. While using a no-op function at runtime may seem like a drawback, it is not likely a high priority for language development; refer to this comment on microsoft/TypeScript#32695, the pull request introducing assertion functions:

Explicitly asserting a control flow type for a variable without casting on every reference would be convenient. Using an asserts function achieves this effect, even though the call appears in the emitted code. Despite this, JavaScript VMs are adept at optimizing away the overhead of calls to empty functions.

Thus, your current options involve either performing a type assertion at each instance where you want to assert the variable's type (redundant yet unseen at runtime), or generating JavaScript code that does not execute any useful operation at runtime but simplifies your TypeScript usage (utilizing an assertion function or copying a type-asserted variable to a new one, etc).

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

Creating a subscription to detect when the mouse button is released during drag and drop operations within an Angular application

I am looking for a way to implement drag and drop functionality in Angular by creating a subscribe inside the onNodeClick() method that listens for when the mouse button is unclicked. ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

Mismatch between TypeScript library and Angular web application: certain properties are absent

I am currently facing a dilemma with my two angular projects. The first one is a library while the second one is a regular Angular webapp. Within my library project, I have the following code snippet: class User { firstName: string; lastName: stri ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

The value specified as type '{ value: BigNumber; }' cannot be assigned to the parameter type 'Overrides & { from?: string | Promise<string> | undefined; }'

I am currently working on a smart contract using Solidity (version 0.8.0) at my buildspace project. Below is a snippet of my code written in TypeScript (4.5.x)/JavaScript and Node.js 16.13.x: ... const waveContractFactory = await hre.ethers.getContractFact ...

The type x cannot be assigned to the parameter '{ x: any; }'

Currently learning Angular and Typescript but encountering an error. It seems to be related to specifying the type, but I'm unsure of the exact issue. Still new at this, so any guidance is appreciated! src/app/shopping-list-new/shopping-edit/shopp ...

Is there a way to specify a type for a CSS color in TypeScript?

Consider this code snippet: type Color = string; interface Props { color: Color; text: string; } function Badge(props: Props) { return `<div style="color:${props.color}">${props.text}</div>`; } var badge = Badge({ color: &ap ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Steps for showing a component (popup modal) just one time with React hooks

Is there a way to implement a popup modal that only appears once using hooks and localStorage? The modal should already appear upon page load. const [showModal, setShowModal] = useState<boolean>(true) return( <ModalIsContractor ...

A step-by-step guide on how to simulate getMongoRepository in a NestJS service

Struggling with writing unit tests for my service in nestjs, specifically in the delete function where I use getMongoRepository to delete data. I attempted to write a mock but couldn't get it to work successfully. Here is my service: async delete( ...

Checking the return data type through modals

Is it possible to specify the type for the returned data in this line modal.onDidDismiss(data =>? It doesn't seem to be working. I want to ensure compile-time type checking for the returned data. Any suggestions? An error is being thrown: [ts] ...

Troubleshooting: Issues with accessing Angular/Typescript Class Getter property

I have a class defined as follows: export class Story { id: number; title: string; storyText: string; utcDate: string; get displayDate(): string { const today = new Date(); const postDate = new Date(this.utcDate); ...

Playing around with TypeScript + lambda expressions + lambda tiers (AWS)

Having trouble importing modules for jest tests in a setup involving lambdas, lambda layers, and tests. Here is the file structure: backend/ ├─ jest.config.js ├─ package.json ├─ babel.config.js ├─ layers/ │ ├─ tsconfig.json │ ├ ...

Tips for managing exceptions in Redux when handling HTTP requests

Currently, I am in the process of learning react alongside redux and redux-observable. My main focus at the moment is on understanding how to handle errors effectively. Here's what I have done so far: I successfully created a redux-observable epic t ...

Hide the tab in React Native's bottom tab navigation when on the current screen within the navigator

Currently, I am delving into learning react native. My project consists of 4 screens, yet I only require 3 buttons on my tab navigator. The objective is to hide or eliminate the active screen's tab from being accessible. Specifically, when on the home ...

What is the method to retrieve the value of a textbox located inside a div with TypeScript?

Here is my HTML structure: <div id="series1"> <div class="col-md-6"> <label for="Mark">Mark</label> <input type="text" id="mark" class="shortTextbox" (blur)="signalSelected('mark')" /> </d ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

The "tsc" command in Typescript seems to be acting up. I've exhausted all possible solutions but

Hello there, I find myself struggling to run Typescript throughout the day while utilizing Visual Studio Code. My usual method involves installing TS globally: $ npm install -g typescript But every time I try to use it, I encounter the same error: bas ...