0

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Related GitHub issue Microsoft/TypeScript#28046
-1

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`)
  }
}

3 Comments

Thanks but I asked for typescript solution not javsscript
@underfrankenwood Typescript is a subset of javascript, so technically this is a typescript solution.
Subset? I think you mean super set. Anyways this is not what I expected. Sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.