typescript - TypeScript,作为对象属性的功能
问题描述
我想将函数存储在对象中,并通过键访问它们而无需调用。
我有一个用键methods
存储的函数命名的对象。string
如果函数是手动分配的,它可以工作,methods["myMethod"]
但是如果我尝试用string
变量分配它,我会得到错误:
element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ myMethod: () => void; }'.
. 我应该怎么理解?
const args = parse(Deno.args);
// Should I define type somehow?
// Maybe something like object<string;Function> in C-like languages?
const methods = {
"myMethod": (): void =>{
console.log("WOOOW");
}
}
if (args.m) {
const methodName: string = args.m;
// works
const method: Function = methods["myMethod"];
// Error: element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ myMethod: () => void; }'.
const methodFromArgs: Function = methods[methodName];
// go
method();
}
解决方案
我methods
用类型{ [key: string]: Function }
而不是默认定义any
,它工作正常。
只要我是 TypeScript 的新手,我就不确定这是否是最佳实践。
const methods: { [key: string]: Function } = {
"myMethod": (): void => {
console.log("WOOOW");
}
}
if (args.m) {
const methodFromArgs: Function = methods[args.m];
methodFromArgs();
}
推荐阅读
- javascript - 按标签排序复选框
- php - 从多个动态字段在数据库中插入一个二维数组 - Laravel
- android - 如何将 React-Native 代码与 Swift 或 Kotlin 联系起来?我应该用每种语言做什么?
- python - 在 Elasticsearch 中添加稀疏向量作为字段
- javascript - postgres 不支持 TypeORM 数组?
- r - 匹配两个不同数据框中的列并减去相应的值
- appium - Appium - 定位没有类名的元素
- javascript - 如何将 Angular 5 应用程序嵌入到另一个页面的 HTML 中?
- knockout.js - ko.contextFor 不使用特定的 DIV 元素来获取上下文模型?
- oracle - 在 Oracle 中将字符 B 替换为 V,反之亦然,Z 替换为 S,反之亦然