Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda