如何将递归联合类型转换为顶层联合

问题描述 投票:0回答:1

假设我有这种类型:

type someUnionType = [1 | 2 | 3,"Some value"] | [4,"Another value"];

我想得到这种类型:

type anotherUnionType = [1,"Some value"] | [2,"Some value"] | [3,"Some value"] | [4,"Another value"];

我试过这个:

type isAUnionAtTopLevel<T, U = T> = U extends any ? [T] extends [U[any]] ? true : false : false;
type convertToFlat<value> = value extends any ? true extends isAUnionAtTopLevel<(infer out extends value)> ? out : never : never;
type someUnionType = [1 | 2 | 3,"Some value"] | [4,"Another value"];
type anotherUnionType = convertToFlat<someUnionType>;

但是 anotherUnionType 只是被设置为 never。 我期望 anotherUnionType 设置为 [1,"Some value"] | [2,“一些价值”] | [3,“一些价值”] | [4、“另一个值”]。

typescript
1个回答
1
投票
type TopLevel<T> = T extends [infer A, infer B] ? A extends any ? [A, B] : never : never; // used to create invidual types 
type someUnionType = [1 | 2 | 3, "Some value"] | [4, "Another value"]; // original union
type anotherUnionType = TopLevel<someUnionType>; // flatten the union

测试用例:

const test1: anotherUnionType = [1, "Some value"];  // PASSED
const test2: anotherUnionType = [4, "Another value"]; // PASSED

const test3: anotherUnionType = [5, "Some value"];  // ERROR
const test4: anotherUnionType = [1, "Wrong value"]; // ERROR
© www.soinside.com 2019 - 2024. All rights reserved.