Exploring the exciting new dynamic module support in TS 2.4 has been a great experience, but I encountered a minor issue along the way:
While using import().then(...), the type of the module is specified. However, I faced a situation where I needed to store the promise for future use without losing the module type information.
I attempted to implement dynamic loading in a wrapper react component (although react-router v4 would have been more suitable) by initiating the load at constructor and triggering a reload when the component is first mounted. Although there was a slight "flickering" issue, the functionality was still effective:
import * as React from 'react'
export class DashboardDynamic extends React.Component<any, any> {
constructor(props) {
super(props)
// At this point, typescript can determine the type of the import, including the "Dashboard" export
this.loaderPromise = import(/* webpackChunkName: "dashboard" */ './Dashboard')
}
componentDidMount() {
// Promise<any> assigns 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 // ISSUE: "any", not module type.
render() {
return this.myContent
}
}
If anyone knows how to correctly define the promise type to preserve the dynamic module's type, I'd greatly appreciate your insights.