TypeScript:使用对象类型中的值重新映射联合类型

时间:2020-03-18 18:39:39

标签: typescript

是否可以使用对象形式的值重新映射打字稿联合类型?

例如我在中途有什么:

type Union = 'item-type' | 'category';
type Special = {
    'item-type': 'itemType';
};

type RemapedValue = [... some realy awesome typescript ...] // => 'itemType' | 'category'

1 个答案:

答案 0 :(得分:2)

我试图写得尽可能清晰。就像黑客一样,但是我认为可以完成工作。

type Union = 'item-type' | 'category' | "test2" | "test-3";
type Special = {
    'item-type': 'itemType';
    'test-3': "test";
};

type UnionExtra = Special & {
    [P in Union]: P
};

type Outersect = {
    [P in keyof UnionExtra]: UnionExtra[P]
}[Union]

type Innersect = {
    [P in (Union & keyof Special)]: Special[P]
}[keyof Special]

type Result = Outersect | Innersect;