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

152
Visualizações
how to get type of a colculated keyof T as a generic type in typescript

I have these two interfaces

interface PersonRequirements{
    user:string,
    password:string,
    id:number
}
export interface Requirement<R> {
    name: keyof R & string,
    save: () => any,/* I want this return type to be same as return type of founded key in R*/
}

and here is my use case elsewhere

const idRequirement:Requirement<PersonRequirements>={
    name:"id",
    save:function ():number/* I want this return type to be same as id's return type(number) but in a generic type safe way*/{
        //
    }
}

I want to make save() return type to be same as id's return type but in a generic type safe way how can I do that ?

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

0

You can declare another generic parameter that takes the property name in at compile time.

export interface Requirement<R, N extends keyof R & string> {
    name: N; // this will force the name property to be the same as being passed in
    save(): R[N];
}

Then using it like this

const idRequirement: Requirement<PersonRequirements, "id"> ={
    name: "id",
    save: () => 0
}
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