I have a type describing an object
type MyObject = {
foo: 1,
bar?: boolean
}
I want to create an array of all keys of given object, and I want TypeScript to notify me whenever my array is incomplete (is missing one or more keys of myObject
), or includes items that are not keys of myObject
.
One way I can think of is
- creating an instance of an intermediary object with the same keys as
myObject
, - using TypeScript to ensure they have they have the same keys
- generating a keys array from that object instance
// The object assignment should throw if I'm missing a key of MyObject
// and I should get `Object literal may only specify known properties` if I add extra props
const intermediaryObject: { [key in keyof Required<MyObject>]: true } = {
foo: true,
bar: true
}
const myObjectKeys = Object.keys(intermediaryObject)
But this gets a bit annoying when working with large objects – is there a way to enforce those constraints without the need for creating intermediary objects?
1