我想我可能会遇到一个带有打字稿的开放错误(https://github.com/microsoft/TypeScript/issues/21760),但我正在有效地试图弄清楚如何从其他文字常量创建映射文字类型。
从下面的 lodash 函数中考虑正确的索引类型结果。
常量结果 = _.mapKeys(en, x => x.display);
export const en = {
ACTIVE: {
ordinal: 0,
display: 'Active',
},
INACTIVE: {
ordinal: 1,
display: 'Inactive',
},
} as const;
// how do i type this?
export const displayToEnum = {};
// actual runtime implementation code
for (const key in en) {
displayToEnum[en[key].display] = en[key];
}
// What i've tried
type Displays = typeof en[keyof typeof en]['display']
type DisplayToEnum = {
// how do i do this dynamically - find the mapped item which fits the conditional constraint
[P in Displays]: P extends typeof en['ACTIVE']['display'] ? typeof en['ACTIVE'] : typeof en['INACTIVE'];
}
export const displayToEnum: DisplayToEnum = {} as any;
for (const key in en) {
displayToEnum[en[key].ordinal] = en[key];
}
// its hardcoded, but this resolves correctly to 0.
const value = displayToEnum['Active'].ordinal;