Home > Net >  Object key based on array values
Object key based on array values

Time:12-06

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?

CodePudding user response:

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

CodePudding user response:

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`)
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related