簡體   English   中英

TypeScript:訪問排除只讀的特定鍵 object literal

[英]TypeScript: Access specific key of excluded readonly object literal

我需要確保bar的值必須是除label之外的任一鍵的c和只讀 object FOO中的d

const FOO = {
  a: {
    label: 'aa',
    value: 'aaa',
  },
  b: {
    label: 'bb',
    value: 'bbb',
  },
  c: {
    label: 'cc',
    value: 'ccc',
  },
  d: {
    label: 'dd',
    value: 'ddd',
  },
} as const;

// enforce assignment here
const BAR = 'aa'; // or 'bb'

解決方案

type FOO_TYPE = typeof FOO;

/*
  FOO_TYPE would give the type of entire object:

  readonly a: {
    readonly label: "aa";
    readonly value: "aaa";
  };
  readonly b: {
    readonly label: "bb";
    readonly value: "bbb";
  };
  readonly c: {
    readonly label: "cc";
    readonly value: "ccc";
  };
*/

// all the keys in FOO
type FOO_KEYS = keyof FOO_TYPE; // "a" | "b" | "c" | "d"

// all the keys except c and d
type EXCLUDED_KEYS = Exclude<FOO_KEYS, 'c' | 'd'>; // "a" | "b"

// enforce the assignment
const BAR: FOO_TYPE[EXCLUDED_KEYS]['label'] = 'aa'; // "aa" | "bb"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM