Creating a connection object for MySql2 in TypeScript within a class

I'm still a beginner when it comes to TypeScript, so I often stumble over simple things. Initially, I had no issues creating a database connection using the code snippet below that was not placed inside a class:

const mysql = require('mysql2');
let connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'myPW',
    database: 'myDb'
});

connection.connect(function(err: any) {
    if (err) {
      return console.error('error: ' + err.message);
    }  
    console.log('Connected to the MySQL server.');
  });

Everything worked perfectly. However, when I attempted to encapsulate the same code within a class like this:

const mysql = require('mysql2');
export class Server {
  constructor() { }

  connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'myPW',
    database: 'myDb'
  });

  connection.connect(function(err: any) {
    if (err) {
      return console.error('error: ' + err.message);
    }    
    console.log('Connected to the MySQL server.');
  });
}

I encountered the following errors:

https://i.sstatic.net/ULN9P.png

The errors displayed are related to the red squiggly line on line 13

Duplicate identifier 'connection'.

Unexpected token. A constructor, method, accessor, or property was expected.

'connect', which lacks a return-type annotation, implicitly has an 'any' return type.

'function' is not allowed as a parameter name.

Duplicate function implementation.

If anyone could kindly guide me on what the issue might be here, I would greatly appreciate it.

Thank you.

Answer №1

The reason for this issue is that the connection.connect section should be placed within the constructor of the class. An improved approach to address this would involve:

import * as mysql from 'mysql2';

export class DatabaseServer {
  public readonly connection: mysql.Connection;

  constructor() {
    this.connection = mysql.createConnection({
      host: '127.0.0.1',
      user: 'root',
      password: 'myPW',
      database: 'myDb'
    });

    this.connection.connect(function(err: any) {
      if (err) {
        return console.error('error: ' + err.message);
      }    
      console.log('Connected to the MySQL server.');
    });
  }
}

By moving the logic into the constructor, we ensure it is in the right place. Placing code directly in the class body will result in an error.

To utilize this class, you can instantiate it like this:

const dbServer = new DatabaseServer();

dbServer.connection.query(...);

Additionally, note that I have changed the require call to an import, following the recommended practice in Typescript.

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

Combining declarations with a personalized interface using TypeScript

My goal is to enhance the express.Request type by adding a user property so that req.user will be of my custom IUser type. After learning about declaration merging, I decided to create a custom.d.ts file. declare namespace Express { export interface ...

Retrieve a specific element from an array list

Hey everyone, I'm facing a problem in my application where I need to extract a specific value from my array and display it in a table for users to see. Check out the code snippet below: Here's my mock data: { "Data": "2020-0 ...

Is there a way to run the mediapipe face detection codepen.io demo on my laptop?

After successfully running the mediapipe face detection demo from Mediapipe official website, I wanted to replicate it on my laptop. To achieve this, I created an 'index.html' file and meticulously transferred the code from the CodePen demo page ...

Make sure to pause and wait for a click before diverting your

Having an issue with a search dropdown that displays suggestions when the search input is focused. The problem arises when the dropdown closes as soon as the input loses focus, which is the desired functionality. However, clicking on any suggestion causes ...

Sending an array from one page to another using Angular 2

I am currently working on a weather application using Angular. As a beginner in Angular, I am facing an issue with sending data to the second page to display the weather information of the selected city. Can someone please help me identify where the proble ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Ensuring that the field remains active in Angular2 even after editing it with a value

When the 3rd dropdown value is selected in the first field dropdown, it enables the 2nd field. However, when I edit and change a different value, since the 2nd field is disabled, I receive null or undefined as the value. I want the 2nd field to retain its ...

Error message: Conflicting type declarations across multiple files

I am facing a challenge with my TypeScript 'snippets' project. It seems that multiple .ts files contain type names (like Foo) that are the same. //file-a.ts type Foo = { } //file-b.ts type Foo = { } When attempting to compile, I encounter ...

Changing Enum Value to Text

In my enum file, I have defined an object for PaymentTypes: export enum PaymentTypes { Invoice = 1, CreditCard = 2, PrePayment = 3, } When I fetch data as an array from the database, it also includes PaymentType represented as numbers: order: ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

Enhancing MUI themes by incorporating module augmentation for multiple typings

I am looking to create a repository with two directories, each using MUI and TypeScript. Both directories will have their own theme defined in one ThemeProvider per root. In the main index.tsx file in the root directory, I want to specify which component t ...

Using a loop variable within a callback function in JavaScript/TypeScript: Tips and tricks

I have a method in my TypeScript file that looks like this: getInitialBatches() { var i = 0; for (var dto of this.transferDTO.stockMovesDTOs) { i++; this.queryResourceService .getBatchIdUsingGET(this.batchParams) ...

What is the proper way to utilize useRef in TypeScript to assign a function to ref?

I am just diving into Typescript and I am looking to assign a function to a ref within a custom hook. My goal is for the function to remain constant throughout renders. Check out the code on CodeSandbox: https://codesandbox.io/s/918l0wro4r function runFu ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...

"X is not compatible with these types of property," but it is not the case

I attempted to instantiate an interface object with properties initialized from another object as follows: id: data.reference.id Even though the properties are compatible, the TypeScript compiler is throwing an error. I am confused about why this is happ ...

In Typescript, we can use a class to encapsulate another class and then return a generic result

Trying to wrap my head around the concept of generic classes, and now I need to dynamically create another class. However, I am uncertain about how to go about it. Class A {} Class B<T> { Return T } Const c = B(A); // which is T More context on w ...

What could be causing FormArrayName to consistently display as undefined in my HTML code, even when the safe-navigation operator is employed

Currently, I'm referring to the Angular Material example found at https://angular.io/api/forms/FormArrayName Upon initializing the packageForm formGroup in ngOnInit() and logging it in the console during ngAfterViewInit(), I can see that the translat ...

The art of crafting informative error log messages in Protractor using TypeScript

I am currently utilizing Protractor, written in typescript, to conduct tests on a live website. I am seeking guidance on how to generate log messages when a Protractor test fails. Presently, the only feedback received is a simple YES/NO message, as shown b ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

Where is the optimal location for placing a JavaScript listening function within an Angular component?

Summary: Incorporating a BioDigital HumanAPI anatomical model into my Angular 5 application using an iFrame. The initialization of the API object is as follows: this.human = new HumanAPI(iFrameSrc); An important API function human.on(...) registers clic ...