首页 > 解决方案 > 如何使用 Typescript 索引匿名对象

问题描述

所以,标题几乎准确地总结了它。我正在做的是将一系列函数导入到名为“ ops.ts ”的索引文件中,并且ops.tsexport使用“ ”语法(下面的代码片段)导出这些函数。然后我ops.ts从另一个文件导入,并动态调用这些函数。一个小问题是我无法通过ops.ts使用字符串键来索引对象(我对 Typescript 不太熟悉,所以我不确定出了什么问题)。具体来说,我得到了错误Element implicitly has an 'any' type because expression of type 'string' can't be used to index type。任何帮助将不胜感激。

以下是相关代码:

ops.ts

export { default as add } from "./ops/add.ts";
export { default as mult} from "./ops/mult.ts";
add.ts

export default function add(a: number, b: number): number {
  return a + b;
}
main.ts
import * as ops from "./ops.ts"
class example {
  //irrelavent code
  constructor() {
     Object.keys(ops).forEach((op: string) => {
        this.operators[op] = ops[op];
     });
  }
}

标签: javascripttypescript

解决方案


这里面有很多东西。

  1. 根据您编译模块的方式,您可以在结果 JS 对象中包含其他字段。Typescript 不允许您对它们进行索引,但是Object.keys()其他迭代键的方法可以。你可能不想在你的数组中有"__esModule": true字段。operations(检查沙箱中的控制台输出:https ://codesandbox.io/s/billowing-lake-x72y3?file=/src/index.ts )
  2. Object.keys()类型是通用的。它可以返回 的数组keyof typeof ops,但为简单起见,它只是string. 而且您通常不能使用任意字符串索引特定类型的对象。你必须明确地转换它,比如operations[key] = ops[key as keyof typeof ops].

至于如何处理,我建议将您的操作作为关联数组导入,因此您实际上不必遍历模块的键。像这样:

//ops.ts
import { default as add } from "./add";
import { default as mult } from "./mult";

export const allOperations = { add, mult }

作为一个自以为是的旁注,我建议避免在 TypeScript 中使用默认导出:https ://basarat.gitbook.io/typescript/main-1/defaultisbad


推荐阅读