Although some sections of the code pertain to AmCharts, the primary focus of the question is related to TypeScript itself.
The JavaScript functions within the AmCharts library perform the following tasks:
export function createDeferred(callback, scope) {
var rest = [];
for (var _i = 2; _i < arguments.length; _i++) {
rest[_i - 2] = arguments[_i];
}
return new Promise(function (resolve, reject) {
registry.deferred.push({
scope: scope,
callback: callback,
args: rest,
resolve: resolve
});
if (registry.deferred.length == 1) {
processNextDeferred();
}
});
}
function processNextDeferred() {
var _a;
var next = registry.deferred[0];
if (next) {
var sprite_2 = (_a = next.callback).call.apply(_a, __spread([next.scope], next.args));
sprite_2.events.on("ready", function () {
next.resolve(sprite_2);
registry.deferred.shift();
if (options.deferredDelay) {
setTimeout(processNextDeferred, options.deferredDelay);
}
else {
processNextDeferred();
}
});
}
}
The crucial aspect is where the callback function is executed and subsequently resolved:
How the library calls and resolves:
var sprite_2 = (_a = next.callback).call.apply(_a, __spread([next.scope], next.args));
next.resolve(sprite_2);
The next.callback
refers to a function from my side:
export function createChartInstance<T extends am4charts.Chart>(
chartId: string,
chartType: new () => T
): T {
const chart = am4core.create(chartId, chartType);
return chart; // returns an instance of the specified chart, such as XYChart
}
const x = await am4core.createDeferred(
createChartInstance,
chartId,
am4charts.XYChart,
);
Following the logic, should not x
also be of type am4charts.XYChart
? Since it was returned from the resolved Promise. However, it is instead of type am4core.Sprite
. Why is this the case? Even though the declaration of createDeferred
is as follows:
export declare function createDeferred(callback: (...args: Array<any>) => Sprite, scope?: any, ...rest: Array<any>): Promise<Sprite>;
The resolved result should indeed be of the chart's type, right?