V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Danswerme

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

  •  
  •   Danswerme · Oct 25, 2021 · 1649 views
    This topic created in 1652 days ago, the information mentioned may be changed or developed.

    代码如下:

    // 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 replies    2021-10-25 20:28:26 +08:00
    Danswerme
        1
    Danswerme  
    OP
       Oct 25, 2021
    暂时用类型断言解决了,但是总感觉怪怪的,v 友们如果有更好的解决方案麻烦回复下。

    ```
    const balalaAlias = <any>balala;

    const module = balalaAlias[key];
    ```
    anjianshi
        2
    anjianshi  
       Oct 25, 2021
    ```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  
       Oct 25, 2021
    const module = balala[key as keyof typeof balala]
    具体可以去了解一下 keyof 和 typeof 的用法
    Danswerme
        4
    Danswerme  
    OP
       Oct 25, 2021
    @anjianshi
    @lzgshsj
    感谢,学习到用法了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   786 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 22:12 · PVG 06:12 · LAX 15:12 · JFK 18:12
    ♥ Do have faith in what you're doing.