Determine type of dynamic module in TS 2.4

Viewed 993

I am greatly enjoying the new dynamic module support in TS 2.4, although I ran into this small issue:

When using import().then(...) the type of the module is given. If I need to store the promise for later, I can't produce a type argument for Promise that conveys the module type info.

I'm trying to do the dynamic load in a wrapper react component (where I should have been using react-router v4), and I want to start loading at constructor - and reload when component are first mounted. There is a "flickering" issue with this, but apart from that it works:

import * as React from 'react'

export class DashboardDynamic extends React.Component<any, any> {
    constructor(props) {
        super(props)

        // At this point typescript knows the type of the import, including the "Dashboard" export
        this.loaderPromise = import(/* webpackChunkName: "dashboard" */ './Dashboard')
    }

    componentDidMount() {
        // Promise<any> makes the {Dashboard} component an "any" type
        this.loaderPromise.then(({Dashboard}) => {
            this.myContent = <Dashboard {...this.props}/>
            this.forceUpdate()
        })
    }

    myContent: JSX.Element = <div />;
    loaderPromise: Promise<any> = null // PROBLEM: "any", not module type.

    render() {
        return this.myContent
    }
}

Anyone who knows how to type the promise so that it will hold the correct type of the dynamic module?

2 Answers

I figured out a way, although ugly:

By separating the load into a function, we can use the wicked way to get return type from function method to get the type. We then get:

const loadDashboard = () => import(/* webpackChunkName: "dashboard" */ './Dashboard')
const loadTypeDummy = (false as true) && loadDashboard()
type IDashboardModule = typeof loadTypeDummy

IDashboardModule is then a promise type that can be used to type the member variable.

UPDATE: With TS 2.8 you can simply do ReturnType<typeof loadDashboard> eliminating the need for the dummy function invocation. Check out the definition of ReturnType, it's awesome.

Related