V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Danswerme
V2EX  ›  TypeScript

TypeScript 怎样动态获取 import * as 导入的内容?

  •  
  •   Danswerme · 2021-10-25 19:28:17 +08:00 · 1053 次点击
    这是一个创建于 885 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下:

    // file1.ts
    export * from "aaa";
    export * from "bbb";
    export * from "ccc";
    export const a = 1;
    export const b = 2;
    
    // file2.ts
    import * as balala from "./file1.ts";
    Object.getOwnPropertyNames(balala)
        .forEach((key) => {
        		const module = balala[key];
        });
    

    在使用balala[key]获取模块时爆红了,提示如下;搜索半天无果,请教下这种情况该怎么解决呢?

    Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("/Users/xxxx/xxx/file1.ts")
    
    4 条回复    2021-10-25 20:28:26 +08:00
    Danswerme
        1
    Danswerme  
    OP
       2021-10-25 19:53:00 +08:00
    暂时用类型断言解决了,但是总感觉怪怪的,v 友们如果有更好的解决方案麻烦回复下。

    ```
    const balalaAlias = <any>balala;

    const module = balalaAlias[key];
    ```
    anjianshi
        2
    anjianshi  
       2021-10-25 20:10:16 +08:00
    ```typescript

    // 先把 balala 从 TypeScript namespace 转换成普通对象,接下来就可以当普通对象来处理了
    const moduleObject = { ...balala }

    Object.getOwnPropertyNames(moduleObject).forEach(key => {
    // 把字符串 key 标识成 moduleObject 的带类型信息的 key
    const o = obj[key as (keyof (typeof moduleObject))]
    console.log(o)
    })

    ```
    lzgshsj
        3
    lzgshsj  
       2021-10-25 20:15:55 +08:00
    const module = balala[key as keyof typeof balala]
    具体可以去了解一下 keyof 和 typeof 的用法
    Danswerme
        4
    Danswerme  
    OP
       2021-10-25 20:28:26 +08:00
    @anjianshi
    @lzgshsj
    感谢,学习到用法了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5098 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:16 · PVG 09:16 · LAX 18:16 · JFK 21:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.