TypeScript:访问被排除的只读对象字面值的特定键



我需要确保bar的值必须是只读对象FOO中除cd外的任何一个键的label

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"