N
N
neroslava2020-07-04 13:14:46
typescript
neroslava, 2020-07-04 13:14:46

How to call a class function through lists in typescript?

in js you can easily do it like this

let test = new Myclass();
let list =['get','set'];
test[list[0]](arg)

but there is an error in ts because it doesn't know what will come to it (Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PacketWriter'.)
how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twoone, 2020-07-04
@neroslava

The reason is described in the error text. You need to use a tuple.

class Flintstone {
    say() {
        console.log(` Yabba-Dabba Do`);
    }
}
let fred = new Flintstone();
let list =['say'] as const;
fred[list[0]];

The same can be done with enumorconst enum
class Flintstone {
    say() {
        console.log(` Yabba-Dabba Do`);
    }
    go() {
        
    }
}
let fred = new Flintstone();

const enum FlintstoneMethod {
    Say = `say`
}

let keys: FlintstoneMethod[] = [FlintstoneMethod.Say];
fred[keys[0]]();

Additionally, deriving class member keys can be automated. But this is already in those cases when you yourself understand why and when it is needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question