I have these two object literals that are supposed to have the same keys, but different values.
Values in obj_1
must be of type FooClass
. Values in obj_2
must be of type string | null
.
const obj_1: Record<string, FooClass> = {
key_1: fooObj1,
key_2: fooObj2,
ket_3: fooObj3,
}
// Unclear what type to set for obj_2
const obj_2 = {
key_1: "fooKey1",
key_2: null,
k4: "fooKey4"
}
Question
How do I type obj_2
such that I get type errors because:
key_3
is present inobj_1
but missing inobj_2
i.e. missing keyk4
is present inobj_2
but not present inobj_1
i.e. extraneous key
Solutions I have considered
String Enum -- I can create a String Enum to list out all the keys, and then use that to type both
obj_1
andobj_2
. However, I expect the keyset to be some 30+ keys and I would like to avoid writing them three times.Inferred Type -- I can remove the type for
obj_1
, then I can set the type forobj_2
usingkeyof typeof obj_1
, which will give a type that is the union of the key literals. This will allow me to satisfy condition 2, but not condition 1. I can use this option if there is another way to ensure that values ofobj_1
are of typeFooClass
.