我之前使用过keyof
运算符来获取对象的键,但我被困在这个简单的代码上。
interface Definition { name: string; visible: boolean; itemIds: number[]; }
const Definitions: { [key: string]: Definition } =
{
line1: { name: 'line 1', visible: true, itemIds: [1, 2, 3] },
line2: { name: 'line 2', visible: true, itemIds: [4, 5, 6, 7] },
next_line: { name: 'next', visible: false, itemIds: [] },
// more items here...
prod: { name: 'production', visible: true, itemIds: [718, 719] },
};
type DefKeys = keyof typeof Definitions; // Wrong!
我想得到的是
DefKeys = 'line1' | 'line2' | 'next_line' | 'prod'
但我实际上得到
DefKeys = string | number
如果我删除对象上的类型约束,我会得到我所期望的,但我会失去类型安全性。
const Definitions = // No type here
{
line1: { name: 'line 1', visible: true, itemIds: [1, 2, 3] },
line2: { name: 'line 2', visible: true, itemIds: [4, 5, 6, 7] },
next_line: { name: 'next', visible: false, itemIds: [] },
// more items here...
prod: { name: 'production', visible: true, itemIds: [718, 719] },
};
type DefKeys = keyof typeof Definitions; // correct
如何将类型保留在对象的定义中并从中获取索引类型?