1

我之前使用过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

如何将类型保留在对象的定义中并从中获取索引类型?

4

1 回答 1

2

您可以将定义创建包装到具有泛型类型参数的函数调用中,并在参数上定义约束。这样原始对象类型将被保留:

function getDefinitions<T extends { [key: string]: Definition }>(definitions: T): T {
    return definitions;
}

const Definitions = getDefinitions({
    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; // "line1" | "line2" | "next_line" | "prod"
于 2019-07-27T12:05:14.733 回答