Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!