首页 > 解决方案 > 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();
}

标签: typescript

解决方案


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();
}

推荐阅读