javascript - 如何使用 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];
});
}
}
解决方案
这里面有很多东西。
- 根据您编译模块的方式,您可以在结果 JS 对象中包含其他字段。Typescript 不允许您对它们进行索引,但是
Object.keys()
其他迭代键的方法可以。你可能不想在你的数组中有"__esModule": true
字段。operations
(检查沙箱中的控制台输出:https ://codesandbox.io/s/billowing-lake-x72y3?file=/src/index.ts ) - 的
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
推荐阅读
- javascript - 物化 CSS 模态
- opencv - 如何使用 OpenCV 或其他图像库在图像上打印文本而不重叠?
- gatsby - src 作为 gatsby-plugin-image 问题中的道具
- bash - 将文件从不同的目录解压缩到不同的目录
- postgresql-9.1 - postgres 中的 to_char (text) 函数使用哪种格式
- python - 无法使用函数获得正确的结果,包括 Python 上的另一个 excel 作家乐趣
- c# - 如何获取 Xamarin Forms iOS 应用程序的调试版本以引发 XamlParserExceptions?
- google-sheets - 如何使用附加图像中的数据提取员工数据
- r - 有条件地停止突变
- python - 用于 PDF 提取的 Pythons 库 pdfreader 不会迭代槽页面