Issue
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
?
Solution
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"
};
Related GitHub issue - Microsoft/TypeScript#28046
Answered By - Guerric P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.