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

401
Views
Typescript - How to return dynamic "object key" that comes from dynamic "prop key value"?

I'm trying to generate "dynamic object key" based of "prop key value" by picking specific object key value.

So let's say I pass in { name: 'someEntity', unrelatedKey: 123 } and I would like to return { someEntity: 'ok' }. How would one do that so the return value is typescript type defined? I've tried something like this but it does not work:

type GetExampleProps = {
  name: string
  unrelatedKey: number
}

type GetExampleRes<T> = {
  [key: T]: string
}

function getExample<T extends GetExampleProps> (props: T): GetExampleRes<T['name']> {
  return {
    [props.name]: 'ok'
  }
}

const example = getExample({ name: 'someEntity', unrelatedKey: 123 })

example.someEntity  // should be valid type string
example.hello       // should be invalid, missing key
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Currently I am unable to do that without a type assertion, but as a temporary solution here it is:

type GetExampleProps<T extends PropertyKey = string> = {
  name: T;
  unrelatedKey: number;
};

function getExample<T extends PropertyKey>(
  props: GetExampleProps<T>
): {
  [K in T]: string;
} {
  const toRet = {
    [props.name]: "a string",
  };

  return toRet as { [K in T]: string };
}

const example = getExample({ name: "someEntity", unrelatedKey: 123 });

example.someEntity;
example.hello; // Property 'hello' does not exist on type '{ someEntity: string; }'

about 4 years ago · Juan Pablo Isaza Report

0

Try this function, this should work the way you need

const createObject = (obj: any) => {
    interface I {
        [name: string]: any;
    }
    const returnObj: I = {};
    returnObj[obj.name] = Object.keys(obj).filter((key) => key !== "name");
    return returnObj;
};
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!