AsExpression Removes Undefined from Type More Swiftly Than I Prefer

Utilizing an API that returns a base type, I employ the as keyword to convert the type into a union consisting of two sub-types of the original base type.

interface base { a: number; }
interface sub1 extends base { s1: number; }
interface sub2 extends base { s2: number; }
interface sub3 extends base { s3: number; }

declare function returns1or2(): base;

const x = returns1or2() as sub1 | sub2;

console.log(x.a);

This approach works effectively and aligns with my requirements.

However, there is a potential issue with the AsExpression in this scenario. If the declaration of the API changes to include --strictNullChecks, the return type may become:

declare function returns1or2(): base | undefined;

const x = returns1or2() as sub1 | sub2;

console.log(x.a);  // triggering a run-time error in certain cases

Such changes do not result in compile-time errors for me as the API user, leading to concerns about using the AsExpression. Are there alternative patterns or strategies that I should consider?

Answer №1

To handle this issue, a simple solution is to introduce an additional layer of abstraction. You can create a custom function that handles the casting without allowing for undefined values:

interface base { a: number; }
interface sub1 extends base { s1: number; }
interface sub2 extends base { s2: number; }
interface sub3 extends base { s3: number; }

declare function returns1or2(): base | undefined;

function castFromTo<From, To extends From>(from: From): To { return from as To };


const x = castFromTo<base, sub1 | sub2>(returns1or2());//error with strictNullChecks 
//Argument of type 'base | undefined' is not assignable to parameter of type 'base'
//      Type 'undefined' is not assignable to type 'base'.

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

What is the importance of having typings when using TypeScript?

I recently came across a post on setting up Material-UI for React with Typescript on Stack Overflow: How to setup Material-UI for React with Typescript? As someone who is brand new to typescript, I initially assumed that typescript was simply a superset o ...

Opening a modal from a different component in Angular 6

I am attempting to launch a modal that is associated with a separate component. However, I encountered an error ERROR TypeError: Cannot read property 'show' of undefined Here is my code: product-catalog.component.html <app-cart-table-modal& ...

Is the Cyrillic encoding feature not functioning properly in Angular 4 with .Net Core 2?

Struggling with handling Cyrillic characters in my current project. Utilizing .Net Core 2 along with Angular 4.2.5 I've noticed that displaying a string in the templates using {{ someCyrillicString }} works fine. However, encountering issues when tryi ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Encountering an issue with TS / yarn where an exported const object cannot be utilized in a consuming

I am currently working on a private project using TypeScript and Yarn. In this project, I have developed a package that is meant to be utilized by one or more other applications. However, as I started to work on the consumer application, I encountered an ...

Unable to utilize Stats.js with @angular/cli version 1.4.4

Attempting to utilize @types/stats with @angular/cli following the guidance at https://github.com/angular/angular-cli/wiki/stories-third-party-lib. However, encountering a tslint error when trying to import * as STATS from 'stats.js'. [ts] Modul ...

How to set up Angular 5 with Express

What is the best way to add Angular 5 to an existing Express project? Below are my files: https://i.stack.imgur.com/DPgMs.png Package.json: https://i.stack.imgur.com/iVVxA.png I am looking to integrate Angular 5 into this express project and develop t ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Wrapper around union function in TypeScript with generics

I'm struggling to find a solution for typing a wrapper function. My goal is to enhance a form control's onChange callback by adding a console.log. Can someone please point out what I might be overlooking? interface TextInput { type: 'Tex ...

Typing a general d3 selection to target various types of SVG elements

I am looking for a callback function that can be utilized with both rect and circle elements. Here is an example: function commonTasks(selection:d3.Selection<PLACEHOLDER_TYPE, MyDataType, SVGGElement, unknown>) { selection .classed('my-c ...

Issue with Angular2: The [routerLinkActive] directive does not update when using _router.navigate

My app includes several routerLinks that I have styled using [routerLinkActive]="['active']". Everything works perfectly when I click on one of the routerLinks to navigate. However, when I try to navigate using: this._router.navigate( [ thisUrl ...

An error is thrown when a try/catch block is placed inside a closure

An issue arises when attempting to compile this simple try/catch block within a closure using TypeScript: type TryCatchFn = (args: any, context: any) => void; function try_catch(fn: TryCatchFn): TryCatchFn { return (args, context) => void { ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this: <div *ngFor="let item of items | async"> <div class="row"> <div class="col-lg-6"> <div class="card ...

Tips for triggering a click event automatically after a 2-minute delay in ReactJS using TypeScript

I need assistance automating a button's onClick function to execute after a 2-minute delay. The current button invokes the handleEventVideos() function. What is the best way to automatically trigger the button click after 2 minutes? I had tried creat ...

What is the process for importing components from a Stencil library into a React application?

After successfully creating: a stencilJS component library named "my-lib" using the "npm init stencil" wizard and an Ionic React app using "ionic start myApp tabs" I am now trying to incorporate the default "my-component," aka MyComponent from my-lib. H ...

Tips for creating an Angular component that can receive a single value from a choice of two different lists

My angular component requires a value that belongs to one of two lists. For example: @Input() public type!: enumA | enumB; However, this setup becomes problematic when the enums share values or are linked together in a way I find undesirable. I would pre ...

Using Material UI with React and TypeScript

I need some assistance with organizing my menus correctly in React using TypeScript. Currently, they are displaying on top of each other instead of within their respective category menus. I have been struggling to find a solution and would appreciate any h ...

Using Rxjs to handle several requests with various headers

I have a specific requirement where, if hasProcessado == true, 10 additional requests should be made before issuing the final request. If the final request fails, 3 more attempts are needed. Furthermore, when sending the last request, it is essential to n ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...