Search code examples
javascriptreactjstypescriptobjectobject-literal

TypeScript: Omit readonly object literal


I need to ensure that the value of bar must be a key of readonly object FOO except the key c.

Code

const FOO = {
  a: {
    // key-value pairs
  },
  b: {
    // key-value pairs
  },
  c: {
    // key-value pairs
  },
} as const;

// all of the keys are assignable
const allKeys: keyof typeof FOO = 'a';

// tried this but TypeScript doesn’t throw error
const bar: Omit<keyof typeof FOO, 'c'> = 'c';

Solution

  • Omit<T, K> is for objects/records and properties, you're looking for Exclude<T, U> which works for unions:

    const bar: Exclude<keyof typeof FOO, 'c'> = 'c'; // error
    

    Playground

    Alternatively, apply the Omit on the record type, and then apply keyof on the result:

    const bar: keyof Omit<typeof FOO, 'c'> = 'c'; // error