1

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:

  1. key_3 is present in obj_1 but missing in obj_2 i.e. missing key
  2. k4 is present in obj_2 but not present in obj_1 i.e. extraneous key

Solutions I have considered

  1. String Enum -- I can create a String Enum to list out all the keys, and then use that to type both obj_1 and obj_2. However, I expect the keyset to be some 30+ keys and I would like to avoid writing them three times.

  2. Inferred Type -- I can remove the type for obj_1, then I can set the type for obj_2 using keyof 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 of obj_1 are of type FooClass.

Sahil
  • 153
  • 3
  • 12
  • 1
    You want `satisfies` instead of a type annotation. On mobile now but if this isn’t answered or pointed at a duplicate when I get back to a real computer I’ll do so – jcalz Apr 20 '23 at 12:15
  • 1
    Okay I'm back; does [this approach](https://tsplay.dev/wE8K3W) meet your needs? If so I'll write up an answer (or probably close this as a duplicate); if not, what am I missing? – jcalz Apr 20 '23 at 13:01
  • 1
    This does exactly what I need. I was not aware of the `satisfies` operator. Thank you! – Sahil Apr 20 '23 at 14:55
  • Okay I linked several previous questions here; good luck! – jcalz Apr 20 '23 at 15:06

0 Answers0