【问题标题】:Determine type of dynamic module in TS 2.4确定 TS 2.4 中动态模块的类型
【发布时间】:2018-01-16 02:09:37
【问题描述】:

我非常喜欢 TS 2.4 中新的动态模块支持,虽然我遇到了这个小问题:

使用 import().then(...) 时,会给出模块的类型。如果我需要存储承诺以备后用,我无法为 Promise 生成传达模块类型信息的类型参数。

我正在尝试在包装反应组件中进行动态加载(我应该一直使用 react-router v4),并且我想在构造函数中开始加载 - 并在首次安装组件时重新加载。这有一个“闪烁”问题,但除此之外它还有效:

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
    }
}

有谁知道如何键入 promise 以使其保持动态模块的正确类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    虽然我不认为像 typeof import('./Dashboard') 这样的东西目前是可能的,但您可以创建一个高阶组件来分解您在 componentDidMount 中获得的内容,同时保留导入的类型。

    会这样输入:

    function dynamicComponent<Props>(loader: () => Promise<React.ComponentType<Props>>): React.ComponentType<Props>
    

    并像这样使用:

    const DynamicDashboard = dynamicComponent(() => import('./Dashboard').then(({ Dashboard }) => Dashboard)))
    

    【讨论】:

    • 这听起来对我来说是个不错的选择。当我有机会测试它时,我会回复。
    • 使用 TS 2.8 可以执行 typeof。请参阅下面的答案。
    【解决方案2】:

    我想出了一个办法,虽然很丑:

    通过将负载分离到一个函数中,我们可以使用wicked way to get return type from function方法来获取类型。然后我们得到:

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

    IDashboardModule 是一个承诺类型,可用于键入成员变量。

    更新: 使用 TS 2.8,您只需执行 ReturnType&lt;typeof loadDashboard&gt; 即可,无需调用虚拟函数。看看ReturnType的定义,厉害了。

    【讨论】:

    • 你能发个链接吗?我的动态导入都没有类型。没有智能感知的生活很糟糕:(
    • @Nickdb93 什么样的链接?使用 TS 2.8,这应该是轻而易举的事,但我没有公开项目可以展示给您。顺便说一句:我不羡慕你现在的处境……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多