I can't understand what is the problem with this code?
import cassandra from "cassandra-driver";
class Cass {
static _cass : cassandra.Client;
this._cass = new cassandra.Client({
contactPoints: ['localhost'],
localDataCenter: 'datacenter1',
keyspace: 'ks1'
});
}
I get the following error at this._cass
assignment line:
Unexpected token. A constructor, method, accessor, or property was expected.ts(1068) Object is possibly 'undefined'.
EDIT
I have a similar class like following that work with no problem, and I am wondering to know why? What is the difference between this class and the previous one?
import mysql from "mysql2";
import { Pool } from "mysql2/promise";
class Pools {
static _pools: Pool;
static connect(options: mysql.PoolOptions) {
this._pools = mysql.createPool(options).promise();
this._pools.execute('SELECT 1 1;');
}
static close() {
this._pools.end();
}
static execute(sql: string, params?: any[] | undefined) {
return this._pools.execute(sql, params);
}
}
export { Pools };
CodePudding user response:
Inside class declarations, you cannot use expressions outside of functions or assignements. Also, you have declared _cass
as static property, so you cannot/should not access it through this
, as it is a property on the class, not the instance.
It think you want to do something like this:
class Cass {
static _cass = new cassandra.Client({
contactPoints: ['localhost'],
localDataCenter: 'datacenter1',
keyspace: 'ks1'
});
}
CodePudding user response:
Properties must be initialized with a value when they are defined or inside the constructor. Try this:
import cassandra from "cassandra-driver";
class Cass {
static _cass: cassandra.Client;
constructor() {
this._cass = new cassandra.Client({
contactPoints: ['localhost'],
localDataCenter: 'datacenter1',
keyspace: 'ks1'
});
}
}