Debian Codegraph @

packages/babel-types/src/modifications/typescript/removeTypeDuplicates.ts

raw
1 import {
2 isIdentifier,
3 isTSAnyKeyword,
4 isTSTypeReference,
5 isTSUnionType,
6 isTSBaseType,
7 } from "../../validators/generated";
8 import type * as t from "../..";
9
10 function getQualifiedName(node: t.TSTypeReference["typeName"]): string {
11 return isIdentifier(node)
12 ? node.name
13 : `${node.right.name}.${getQualifiedName(node.left)}`;
14 }
15
16 /**
17 * Dedupe type annotations.
18 */
19 export default function removeTypeDuplicates(
20 nodes: Array<t.TSType>,
21 ): Array<t.TSType> {
22 const generics = new Map<string, t.TSTypeReference>();
23 const bases = new Map<t.TSBaseType["type"], t.TSBaseType>();
24
25 // store union type groups to circular references
26 const typeGroups = new Set<t.TSType[]>();
27
28 const types: t.TSType[] = [];
29
30 for (let i = 0; i < nodes.length; i++) {
31 const node = nodes[i];
32 if (!node) continue;
33
34 // detect duplicates
35 if (types.indexOf(node) >= 0) {
36 continue;
37 }
38
39 // this type matches anything
40 if (isTSAnyKeyword(node)) {
41 return [node];
42 }
43
44 // Analogue of FlowBaseAnnotation
45 if (isTSBaseType(node)) {
46 bases.set(node.type, node);
47 continue;
48 }
49
50 if (isTSUnionType(node)) {
51 if (!typeGroups.has(node.types)) {
52 nodes.push(...node.types);
53 typeGroups.add(node.types);
54 }
55 continue;
56 }
57
58 // todo: support merging tuples: number[]
59 if (isTSTypeReference(node) && node.typeParameters) {
60 const name = getQualifiedName(node.typeName);
61
62 if (generics.has(name)) {
63 let existing: t.TypeScript = generics.get(name);
64 if (existing.typeParameters) {
65 if (node.typeParameters) {
66 existing.typeParameters.params = removeTypeDuplicates(
67 existing.typeParameters.params.concat(node.typeParameters.params),
68 );
69 }
70 } else {
71 existing = node.typeParameters;
72 }
73 } else {
74 generics.set(name, node);
75 }
76
77 continue;
78 }
79
80 types.push(node);
81 }
82
83 // add back in bases
84 for (const [, baseType] of bases) {
85 types.push(baseType);
86 }
87
88 // add back in generics
89 for (const [, genericName] of generics) {
90 types.push(genericName);
91 }
92
93 return types;
94 }