Check if keys of Object B existing within Object A exist within another array value of a key in Object A

  Kiến thức lập trình

Example code:

enum ENUM_A { 
  ONE="ONE",
  TWO="TWO",
  THREE="THREE",
  FOUR="FOUR"
}

interface TYPE_A {
  myArray: ENUM_A[],
  mySpecificMapping: {
    [key in ENUM_A]?: boolean
  }
}
const myObject: TYPE_A = {
  myArray: [ENUM_A.ONE, ENUM_A.THREE],
  mySpecificMapping: {
    [ENUM_A.ONE]: true,
    // Uncommenting the line below should result in a TypeScript error
    // [ENUM_A.TWO]: true,
    [ENUM_A.THREE]: true,
    // Uncommenting the line below should result in a TypeScript error
    // [ENUM_A.FOUR]: true,
  }
}

myObject should error if “mySpecificMapping” contains keys that don’t exist within “myArray”

I think I need to use self referencing types here?

LEAVE A COMMENT