繁体   English   中英

基于数组值的 Object 键

[英]Object key based on array values

我有数组: const arr = ['foo', 'bar', 'bax'];

我想根据数组条目创建一个 object:

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

如何告诉 typescript obj的所有键都必须在arr内?

你可以这样做:

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操场

相关 GitHub 问题 - Microsoft/TypeScript#28046

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM