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

112
Visualizações
Declare recursivley method chaining in TypeScript

I have the following function that returns dynamic object in vanilla JS:

function myFunc(props) {
  return Object.keys(props).reduce((acc, key) => ({
    ...acc, [key](val) {
      console.log(val);
      return this;
    } 
  }), {});
}

And an object with that function above:

const myProps = {
  counter: 0,
  isCounting: false,
}

const obj = {
  myFunc: myFunc(myProps),
  anotherFunc: () => {},
  moreFunc: () => {},
}

And I want to decalre this object in my .d.ts file but I'm not sure what is the best way to define a type for recursive method chaining..

I tried using the following type:

type Obj<T> = {
  myFunc: () => Record<keyof T, () => this>;
  anotherFunc: () => void;
  moreFunc: () => void;
}

But the this keyword is referring to the type instance itself and not the myFunc object. Meaning I get also the anotherFunc and moreFunc in it instead of just the dynamic keys from myProps.

Can someone help with this implementation?

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

0

You can define this in a TypeScript interface:

interface Obj {
    [key: string]: (val: string) => this
}

const obj: Obj = {
  foo(val) {
    console.log('foo:', val);
    return this;
  },
  bar(val) {
    console.log('bar:', val);
    return this;
  }
}

I've assumed that the val arguments are string.

Edit: I've just seen your comment on your post - you can capture the key dynamically with [key: string]. I've updated my answer.

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