In a strict mode environment, Typescript warns when a variable is being used before it has been

I'm having an issue while using database transaction to create a Page record. Despite the fact that this.pagesService.create() only returns Page and will throw an error if something goes wrong, I keep receiving a

Variable 'createdPage' is used before being assigned
error. Therefore, the program should guarantee that createdPage is set if no exception is thrown. Why am I encountering this error?

  @Post('')
  async create(
    @Body() body: PageCreateDto,
  ): Promise<Page> {
    let createdPage: Page;
    try {
      await this.database.transaction(async trx => {
        createdPage = await this.pagesService.create(body, trx);
      });
    } catch (error) {
      throw new InternalServerErrorException('unable to create page');
    }

    return createdPage;
    
  }

Answer №1

The issue here lies in the asynchronous nature of the function passed into the transaction call, causing uncertainty around the assignment of createdPage when returning it. One way to address this is by implementing a promise.

@Post('')
async create(@Body() body: PageCreateDto): Promise<Page> {
  return new Promise<Page>((resolve, reject) => {
    try {
      await this.database.transaction(trx => this.pagesService
        .create(body, trx)
        .then(resolve));
    } catch (error) {
      reject(new InternalServerErrorException('unable to create page'));
    }
  }); 
}

Answer №2

Resolution of the issue by returning it inside an arrow function:

  @Post('')
  async create(
    @Body() body: PageCreateDto,
  ): Promise<Page> {
    let createdPage: Page;
    try {
      createdPage = await this.database.transaction(async trx => {
        return this.pagesService.create(body, trx);
      });
    } catch (error) {
      throw new InternalServerErrorException('unable to create page');
    }

    return createdPage;
    
  }

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

When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once. HTML <!DOCTYPE ht ...

Transformer Class: An object containing properties that are instances of another class

class ClassA { x: number; y: number; sum(): number { return this.x + this.y; } } class ClassB { @Type(() => ClassA) z: {[key: string]: ClassA}; } const b = transformObject(ClassB, obj); const z = b.z[key]; const s = z.s ...

update the variables based on the changes in the service

I have developed a service in my application to retrieve configuration settings from the database. This service is used to display various configurations across different parts of the app. However, I am encountering an issue where the variables do not upda ...

What's the reason "console.log()" doesn't function on this particular site?

When I go to https://www.google.com/ and enter console.log("Hello world!") into the Chrome DevTools console, it prints "Hello world!" as expected. However, when I try the same command on , nothing shows up in the console. Why doesn't it work for this ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...

When a StaticFiles instance is mounted, FastAPI will issue a 405 Method Not Allowed response

Running a FastAPI application has been smooth sailing until I encountered an issue. In my current setup, the application script is as follows: import uvicorn from fastapi import FastAPI from starlette.responses import FileResponse app = FastAPI() @app.ge ...

Is it possible to remove a form element without relying on jQuery's .remove() method?

Looking to hide the select all checkbox from users without actually removing it when submitted. The challenge lies in making the removal of the select all checkbox seamless on the front end, while ensuring it is not sent to the server. Is there a way to ...

Encountering a 404 error while using Angular HTML5Mode setting

I recently enabled pretty URLs in my Angular application by switching to html5mode. However, whenever I try to refresh the page, I encounter a 404 error. For instance, if I access my app through , everything functions as expected. But when I attempt to r ...

Controlling Navigation Bar State

Looking to enhance my app by implementing state management for better flexibility. In essence, my app is a React web app integrated with Tableau dashboards. I aim to have specific routes (each containing specific dashboards) dynamically populated in the ap ...

Control or restrict attention towards a particular shape

Greetings! I am seeking guidance on how to manage or block focus within a specific section of a form. Within the #sliderContainer, there are 4 forms. When one form is validated, we transition to the next form. <div #sliderContainer class="relativ ...

What is the best way to access a variable within the .each() function in jQuery?

One common dilemma often faced is figuring out how to ensure that markup remains accessible within the scope of this .each() function. Instead of focusing solely on resolving this specific issue, my interest lies more in discovering a method to access ext ...

Exploring the depths of nested collections in Angular 12

As I work on my very first Angular/Firestore app, I find myself grappling with understanding how to retrieve data from nested collections. The Firestore database path that I need to access is as follows: /Customer(CollectionName)/cl0Apvalb6c0w9hltQ8AOTF4go ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

What are some ways to find your way without using the Navigator app?

Navigator.js const App = createStackNavigator({ screenA: { screen: ScreenA }, screenB: { screen: ScreenB } }) const Navigator = createAppContainer(App); export default Navigator; App.js return ( <SafeAreaView> <Provider store={ ...

What is the best way to implement a promise function in this scenario using JavaScript?

I am currently working on an app using AngularJS and the MediaFire JavaScript SDK to perform various tasks. One specific task I am struggling with is creating a folder during an upload process, which returns a 'folderkey'. I would like to use .t ...

Utilizing Vue.js: Dynamically linking v-model to route parameters depending on the current state

I'm currently in the process of developing an application that will serve as the backbone for a restaurant chain's website. The main functionality involves allowing users to modify page content and images. Given the complexity of the site with it ...

Creating custom functionality by redefining methods in Typescript

My current scenario is as follows: abstract class A implements OnInit{ ngOnInit() { this.method(); } private method() { // carrying out tasks } } class B extends class A implements OnInit { ngOnInit() { thi ...

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

What is the best way to define the type of an object in TypeScript when passing it to a function

I am currently working on a function that accepts an object of keys with values that have specific types. The type for one field is determined by the type of another field in the same object. Here is the code: // Consider this Alpha type and echo function. ...