简体   繁体   中英

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';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM