且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在动态导入中使用类型?

更新时间:2022-05-14 03:00:04

XLSX 仅表示导入的值,而不表示类型.

XLSX will only represent the value of the import, not the types.

您有两个选择.

使用导入类型:

import('xlsx').then(XLSX => {
    const wb: import('xlsx').WorkBook = XLSX.read(bstr, { type: 'binary' });
})

您可以定义类型别名来简化此操作: type WorkBook = import('xlsx').WorkBook

You can define a type alias to make this easier: type WorkBook = import('xlsx').WorkBook

导入类型:

import { WorkBook } from 'xlsx' // Just for the type, will be elided in this example

import('xlsx').then(XLSX => {
    const wb: WorkBook = XLSX.read(bstr, { type: 'binary' });
})

第二种选择比较棘手,如果仅使用静态导入类型中的导入,则应该省略import语句(即不输出到JS).一旦您在表达式中使用了静态导入中的任何导入(即,将在JS中结束的任何位置),导入就不会被忽略.查看有关被删除的模块的更多信息

This second option is more tricky to get right, if you only use the imports from the static import in types, the import statement should be elided (ie not outputted to JS). As soon as you use any import from the static import in an expression (ie. any position that will end up in the JS) the import will not be elided. See more about module being elided