Artem Skibin
Artem Skibin

Reputation: 111

How to define a class with dynamic keys?

I need to define a class with dynamic props like 'Methods'. I wrote this

type Methods = {
    [name:string]:Function
}

class App <M extends Methods> { 
    [name: keyof M] : M[name] // dont work
}

var methods = {
    action : Function,
    move : Function
}

type M = keyof typeof methods;

type myApp = App<typeof methods>;

but I get the following errors. Can these be fixed?

An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.

'name' refers to a value, but is being used as a type here. Did you mean 'typeof name'?

Return type of index signature from exported interface has or is using private name 'name'.

Reproducible example

Upvotes: 2

Views: 545

Answers (1)

Bergi
Bergi

Reputation: 665130

You seem to be looking for mapped types. Those only work for type declarations, not for classes though:

type App<M extends Methods> = { 
    [name in keyof M]: M[name];
}

(Full demo)

If you actually want to define a class, you need to do it with a concrete type:

var methods = {
    action: Function,
    move: Function
}
type MyApp = App<typeof methods>;

class TheApp implements MyApp {
    action!: typeof Function;
    move!: typeof Function;
    constructor() {
        Object.assign(this, methods);
    }
}

Upvotes: 2

Related Questions