typescript

TypeScript, function as an object property


I would like to store functions in object and access to them by a key without call.
I have object named methods with functions stored with a string key. It works if function is assigned manually methods["myMethod"] but if I try to assign it with string variable I get error:

element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ myMethod: () => void; }'.. How should I understand it?

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

Solution

  • I've defined methods with type { [key: string]: Function } instead of default any and it works fine.
    As long as I am new to TypeScript I am not sure if it is best practice.

    const methods: { [key: string]: Function } = {
        "myMethod": (): void => {
            console.log("WOOOW");
        }
    }
    
    if (args.m) {
        const methodFromArgs: Function = methods[args.m];
        methodFromArgs();
    }