Search code examples
angulartypescript-typingsamcharts

How to use namespace of lazy loaded modules


I have an Angular application that uses the AmCharts library. In order to use the charts I want to lazy load AmCharts and they suggest doing it with promises. The issue I'm having is that it seems that type inference doesn't work and I'd like to specify the types of the constants I'm creating.

Promise.all([
        import("@amcharts/amcharts4/core"),
        import("@amcharts/amcharts4/charts"),
        import("@amcharts/amcharts4/themes/animated"),
      ]).then((modules) => {
        const am4core = modules[0];
        const am4charts = modules[1];
        const am4themes_animated = modules[2].default;

        ...

        const valueAxis: am4charts.ValueAxis = chart.yAxes.push(
          new am4charts.ValueAxis()
        );

If I'd import the modules at the top the valueAxis declaration would work but now I get an error on am4charts of am4charts.ValueAxis that namespace does not exist. Is there any way I could get this to work?


Solution

  • In typescript you can import only the types and it seems to be doing the trick

    So in my code I now have:

    import type * as am4chartsTypes from "@amcharts/amcharts4/charts";
    import type * as am4coreTypes from "@amcharts/amcharts4/core";
    ...
    
    
    export class Chart {
      private chart?: am4chartsTypes.XYChart;
    
      ngAfterViewInit() {
        ... 
        
        this.chart = am4core.create(
            this.chartWrapper.id,
            am4charts.XYChart
        );
        ...
      }
    
    }