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

185
Views
Object key based on array values

I have array: const arr = ['foo', 'bar', 'bax'];

I want to create an object based on array entries:

const obj = {
  foo: true,
  bar: true,
  bax: false,
  fax: true, // typescript should show error here because "fax" is not in "arr"
};

How to tell typescript that all keys of obj must be inside arr?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can do like this:

const arr = ['foo', 'bar', 'bax'] as const;

type MappedObject = Record<typeof arr[number], boolean>;

const obj: MappedObject = {
  foo: true,
  bar: true,
  bax: false,
  fax: true, // typescript should show error here because "fax" is not in "arr"
};

TypeScript playground

Related GitHub issue - Microsoft/TypeScript#28046

about 4 years ago · Juan Pablo Isaza Report

0

const arr = ['foo', 'bar', 'bax'];

//I want to create an object based on array entries:

const obj = {
  foo: true,
  bar: true,
  bax: false,
  fax: true, // typescript should show error here because "fax" is not in "arr"
};

for(const [key, value] of Object.entries(obj))
{
  if(!arr.includes(key))
  {
    console.log(`error, ${key}: ${value} not found in array`)
  }
}

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!