The parameter cannot accept a value of type 'number | null' even if it is not null

I'm puzzled about the error I'm encountering in TypeScript: "Argument of type 'number | null' is not assignable to parameter of type 'number'", even though I have already checked if my variable is not null.

Is there any other solution apart from double-checking if my variable isn't null after subscribing?

Here's an example:

    if (this.myVariable) {
      this.dialogService
          .openConfirmDialog('TITLE', 'CONTENT')
          .afterClosed()
          .pipe(take(1))
          .subscribe((userChoice: boolean) => {
            if(userChoice){
              this.restFacadeService
                  .archiveBook(this.myVariable) //This is where the error occurs
                  .subscribe(() => { 
                    this.createCustomBook();
                  })
            }
      });
    } else { this.createCustomBook(); }

Answer №1

if (this.myVariable) {

Prior to the subscribe callback being executed, you checked for the existence of it. However, there is a possibility that its value may have changed in the meantime. Typically, narrowing the type of a variable in one part of the code does not carry over to nested callback functions.

To mitigate this issue, you can either store the value in a separate immutable variable:

if (this.myVariable) {
  const saved = this.myVariable; // saved will always be a number
  this.dialogService
    // ...  
    .subscribe((userChoice: boolean) => {
      if (userChoice) {
        this.restFacadeService
          .archiveBook(saved) // still infers as a number
          // ...
      }
    })

Alternatively, you could recheck the value of this.myVariable within the subscribe callback.

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

Unveiling the secret to implementing conditional rendering within a flatlist

I gathered data from an API that provides information on country names and populations. The country names are displayed in a searchable flatlist. My objective is to show a small circle next to each country name in the flatlist based on its population size. ...

Error message: "The function platform_browser_dynamic_1.bootstrap does not exist in Angular 2."

I had everything set up and running smoothly until suddenly I started receiving this error out of nowhere: TypeError: platform_browser_dynamic_1.bootstrap is not a function Here's the component I've been working on: import { Component, Input, ...

The journey of communication: uncovering the essence of @input between parent and

I'm diving into Angular and currently working on the @Input phase. Within my main app, there's a child component. Inside app.component.ts, I've declared a test variable that I wish to pass from app.component.ts to child.component.ts. // ap ...

Why does Typescript keep displaying a warning that it cannot locate module xxx?

It's puzzling why I keep receiving this warning when everything seems to be working correctly. https://i.sstatic.net/uKB8G.png This warning is related to the tsconfig.json file generated by Nuxi: // Generated by Nuxi { "compilerOptions&qu ...

Challenges with React Event Listener Types

https://i.sstatic.net/cVlpr.png useEffect(() => { const handleEscClose = (e: KeyboardEvent) => { if (e.key === 'Escape') changeVisibility(); }; if (isVisible) document.addEventListener('keydown', handleEscClos ...

Angular2 - Retrieve data in XLS format from RestService并下载

I am looking to create a web service using Apache POI to generate an Excel file (xls, xlsx). Below is the snippet of code I have put together: @RequestMapping(value = "/export", method = RequestMethod.GET) public void exportXlsx(HttpServletResponse respon ...

Endlessly calling a function binding to a property

I've come across a very peculiar issue in my Angular application. Imagine I have a simple example.component.ts @Component({ moduleId: module.id.toString(), selector: 'example', templateUrl: 'example.component.html', ...

Creating Observable in Angular 5视Render

As I attempt to display an Observable in Angular, I encounter an issue where nothing appears on the browser despite making a request to an API for data. Here is the service responsible for retrieving information about a single user: export class UserServ ...

Having trouble getting the Next.js Custom Server to function properly with Firebase

I have deployed my Next.js App on Firebase and I am using a custom server (server.ts) to launch the app (node src/server.ts). The code for the server.ts file along with firebaseFunctions.js is provided below. The server.ts file works fine locally, which ...

There was an issue with vite-plugin-pages stating that it could not locate the module '~pages' or its corresponding type declarations

Currently working on my Vue project, using TypeScript with Vite. To handle routing, I am utilizing the 'vite-plugin-pages' plugin. Encountered a type error while importing routes from the '~pages' directory. Here's a snippet of m ...

A guide on utilizing Material UI Fade for smoothly fading in a component when a text field is selected

I am facing an issue with a text field input and a helper component. My goal is to have the helper component fade in when a user focuses on the input field. The helper component is wrapped as follows: <Fade in={checked}> <DynamicHelperText lev ...

Angular 4 routerLink displaying incorrect component

I have set up my app-routing.module.ts with the following routes: const appRoutes: Routes = [ {path: '', component: MainComponent, children:[ {path: '', component: AppComponent, children:[ {path: 'home', component ...

"Omitting the parameter value when passing it to a directive in Angular

I recently developed a Directive in Angular7, but I encountered an issue when trying to pass a string value from the HTML to the directive. When using the following code snippet in my HTML: <ng-template [appValidatePermission]='CreateRole'&g ...

Leverage advanced type deduction in Key Remapping

I'm puzzled by this code snippet: type Foo<T extends string> = [T] extends [infer Y] ? Y : never // works fine type Test_2<T extends Array<string>> = { [P in T[number] as Foo<"foo">]: undefined } // no issues type ...

Manipulating Typescript JSON: Appending child attributes and showcasing them alongside the parent item attributes

Here is a JSON data that needs to be processed: var oldArr = [{ "careerLevel": "Associate", "careerLevels": [ { "201609": 21, "201610": 22, "careerID": "10000120" }, { "201609": 31, "201610": 32, ...

What is the reason for VS Code recognizing an import as valid while WebPack does not approve it?

I believe the root of the problem lies in the version of WebPack I am using ("webpack-cli": "3.3.11"). Before embarking on another round of debugging to upgrade WebPack (attempted version 5 but faced issues due to lack of a config file) ...

Testing Angular Components Using HostListener

I am looking to write unit tests for @HostListener, but I'm unsure of how to go about it since it's located on top of the component. Here is an example of the code: @HostListener('document:click', ['$event']) onDocumentClick ...

What's the most effective method for transferring data to different components?

How can I efficiently pass a user info object to all low-level components, even if they are grandchildren? Would using @input work or is there another method to achieve this? Here is the code for my root component: constructor(private _state: GlobalSta ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

Encountering Error 203 while trying to establish a connection between Angular and Django Rest Api

I'm currently working on a project that involves creating a contacts system, but I've been encountering errors when trying to list them. Interestingly, I can successfully perform CRUD operations using Postman with the API. One of the messages I ...