[英]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.