代码如下:
// 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")
1
Danswerme OP 暂时用类型断言解决了,但是总感觉怪怪的,v 友们如果有更好的解决方案麻烦回复下。
``` const balalaAlias = <any>balala; const module = balalaAlias[key]; ``` |
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) }) ``` |
3
lzgshsj 2021-10-25 20:15:55 +08:00
const module = balala[key as keyof typeof balala]
具体可以去了解一下 keyof 和 typeof 的用法 |