Debian Codegraph @

packages/babel-types/src/builders/typescript/createTSUnionType.ts

raw
1 import { tsUnionType } from "../generated";
2 import removeTypeDuplicates from "../../modifications/typescript/removeTypeDuplicates";
3 import { isTSTypeAnnotation } from "../../validators/generated/index";
4 import type * as t from "../..";
5
6 /**
7 * Takes an array of `types` and flattens them, removing duplicates and
8 * returns a `UnionTypeAnnotation` node containing them.
9 */
10 export default function createTSUnionType(
11 typeAnnotations: Array<t.TSTypeAnnotation | t.TSType>,
12 ): t.TSType {
13 const types = typeAnnotations.map(type => {
14 return isTSTypeAnnotation(type) ? type.typeAnnotation : type;
15 });
16 const flattened = removeTypeDuplicates(types);
17
18 if (flattened.length === 1) {
19 return flattened[0];
20 } else {
21 return tsUnionType(flattened);
22 }
23 }