Do you know the origin of this library? The individual responsible for writing it needs to be addressed. It seems like a mistake (given that they never tested it) or perhaps intentionally malicious: using the almost-reserved word constructor
as an identifier for an instance method is simply inviting trouble.
UPDATE 2019-04-25: The consequences go beyond just being a questionable idea; it appears that with forthcoming native support in JavaScript for class fields, having a property named "constructor"
within a class will become an error. TypeScript is set to adjust for this starting from version 3.5 onwards, rendering the current implementation outdated. Refer to the recent GitHub issue Microsoft/TypeScript#31020 for more details. Post-TS3.5, having a class with an instance constructor
property that isn't the actual constructor function itself might not be viable.
The author of the library likely either meant to reference a genuine constructor callable via new
, in which case they should consider something akin to @Series0ne's recommendation; or, if the intention was truly to employ an instance method for object initialization, choosing a conventional method name such as init()
would be more appropriate.
In any scenario, accepting the provided interface and especially implementing it is ill-advised.
Lets proceed with an attempt at implementation:
export class LatLngImpl implements LatLng {
private _lat: number;
private _lng: number;
lat() {
return this._lat;
}
lng() {
return this._lng;
}
// crucial section, though refer to Microsoft/TypeScript#31020
"constructor"(lat: number, lng: number) {
this._lat = lat;
this._lng = lng;
}
}
The workaround involves utilizing the string literal "constructor"
instead of the bare word constructor
. According to the TypeScript specification:
String literals can be employed to assign non-standard identifiers to properties
By opting for the string literal, we manage to define it as an instance method rather than the static class constructor method invoked during new
calls, facilitating smooth compilation.
We can now utilize it, should we dare:
const latLng = new LatLngImpl();
latLng.constructor(47.6391132, -122.1284311); // 😠 Why not init()?
console.log("Latitude: " + latLng.lat() + ", Longitude: " + latLng.lng());
Regrettably, daring stands mistaken.
REVISITING 2019-04-25 The aforementioned quoted-string implementation will no longer be operational post TypeScript 3.5, with the correct response being "this cannot be done" and "opt for a real constructor instead".
Hoping this clarifies matters; best of luck!