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.