I want to call a method automatically when a TS class is accessed, similar to java's static{ }
.
For example, if I implement a constants class in Java:
public class Constants
{
public static final String FOO;
static
{
// ... creates a http request ...
FOO = // ... gets "http:/.../api/foo" from server
}
}
How can I implement something like this in TypeScript?
Currently, I'm using:
export class Constants
{
public static FOO;
public static ensureInitialized(callback)
{
if (this.FOO == null)
{
let request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
FOO = request.responseText;
callback();
}
};
request.open('POST', "http:/.../api/foo", true);
request.send('');
}
else callback();
}
}
But that requires an active call to ensureInitialized()
to all the methods using this constant. Are there any TS equivalent to static{ }
in Java?