【问题标题】:How can I use the types of a conditionally imported module in typescript?如何在打字稿中使用条件导入模块的类型?
【发布时间】:2021-12-08 11:45:05
【问题描述】:

我的项目中有一个可选且依赖于平台的依赖项,我想像这样有条件地导入:

import os from 'os';

export default async function doSomething(): Promise<foo | null> {
  if(os.type() === 'some os') {
    // "platform-dependent-module" exposes type "foo"
    const module = await import("platform-dependent-module");
    // do stuff
    return bar; // bar is of type foo
  }
  return null;
}

但是这不起作用,因为编译器Cannot find name 'foo'。是否可以在不必静态导入模块的情况下公开类型定义?

【问题讨论】:

    标签: javascript node.js typescript es6-modules dynamic-import


    【解决方案1】:

    显然,可以分别导入和暴露类型。所以可以像这样静态导入类型:

    import type {foo} from 'module
    

    并在动态加载整个模块之前使用类型。最终代码如下所示:

    import os from 'os';
    import type {foo} from 'platform-dependent-module';
    
    export default async function doSomething(): Promise<foo | null | Error> {
      if(os.type() === 'some os') {
        try {
          // "platform-dependent-module" exposes type "foo"
          const module = await import('platform-dependent-module');
          // do stuff
          return bar; // bar is of type foo
        } catch (e) {
          return e;
        }
      }
      return null;
    }
    

    【讨论】:

      【解决方案2】:

      是的,您可以使用TypeScript's Type Aliases

      还要确保返回类型应该是异步函数中的承诺。

      并且catch关键字应该替换为else,但不需要else

      import os from 'os';
      
      type foo = any;
      
      export default async function doSomething(): Promise<foo | null> {
        if(os.type() === 'some os') {
          // "platform-dependent-module" exposes type "foo"
          const module = await import("platform-dependent-module");
          // do stuff
          return bar; // bar is of type foo
        }
        return null;
      }
      
      

      【讨论】:

      • 但这有什么意义呢?它不会让它Promise&lt;any | null&gt;吗?那不是没有意义吗?
      • @KerimGüney 我不知道这里foo 的返回类型的目的是什么。在我看来,我想;也许它是一种自定义数据类型。或者它是一个类。不确定.. 你可以替换 Promise&lt;any | null&gt; 没关系。但是如果只有foo。 ts 编译器不知道这是从哪里来的。甚至 js 编译器。因为它是未定义的。所以你应该定义它或将它声明为一个类型。当声明为一种类型时,它被认为是全局的。
      • @KerimGüney 如果您不知道该模块的类型,请参考typescriptlang.org/docs/handbook/2/functions.html#unknown。您可以将返回类型设置为未知或任何也可以。
      • 感谢您的意见。 foo 是由条件导入模块定义的自定义类型。我希望有一些方法可以只加载模块的类型,所以我可以将它们用作返回类型。这样看来,任何有条件地加载模块的函数都只会返回 anyunknown 的一些变体,这真是太糟糕了。
      • @KerimGüney 如果模块导出其类型,那么您可以。否则,您必须自己定义,简单。
      猜你喜欢
      • 2021-02-03
      • 2016-04-12
      • 2023-02-13
      • 2018-05-24
      • 1970-01-01
      • 2020-01-03
      • 2017-04-11
      • 1970-01-01
      • 2021-05-08
      相关资源
      最近更新 更多