0

I’m new to TypeScript so simple things still trip me up. I successfully created a database connection using the code below which was not in 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.');
  });

All was fine. Then I put this same code inside of 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.');
});
}

and the I got these errors:

enter image description here

The errors below come from the red squiggly on line 13

Duplicate identifier 'connection'.

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

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

'function' is not allowed as a parameter name.

Duplicate function implementation.

Can someone kindly explain what I'm doing wrong here?

Thank you.

1 Answer 1

1

This is happening because the connection.connect part belongs inside the constructor of the class. A better way to write this would be

import * as mysql from 'mysql2';

export class Server {
  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.');
    });
  }
}

This moves the logic into the constructor, which is where logic should be. Putting code in the class body will raise an error.

If you wanted to use this class, you could do it as so:

const server = new Server();

server.connection.query(...);

Also note that I have converted the require call into an import, which is the recommended way in Typescript.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @anut. That solved that problem. The next comment is the syntax for how I executed a stored procedure previously which worked. However, how ti throws an error which I will post after:
server.connection.query('CALL spix_Trace_lstForReview(\"2022-1-1\", \"2022-7-7\" )', function (error: any, results: Array<any>, fields: any) { if (error) throw error; console.log(results); results.forEach(result => { console.log(result.Name); }); }); This file is being treated as an ES module because it has a '.js' file extension and 'D:\Apps\zDeleteme\TS_D2_webpack2\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
@spacedog This is because your tsconfig.json doesn't work with your package.json. Try adding "module": "ESNext" in compilerOptions in tsconfig.json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.