Skip to content

Commit

Permalink
fix: handling imported types as array in union and referenced in tupl…
Browse files Browse the repository at this point in the history
…es (#229)

* test: adding failing tests

* fix: handle tuple in type extractor

* test: adding weird test to cover edge cases
  • Loading branch information
tvillaren committed Apr 12, 2024
1 parent 8aaf2b9 commit b797dd0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
45 changes: 45 additions & 0 deletions src/utils/traverseTypes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ describe("traverseTypes", () => {
expect(result).toEqual(["Superhero", "Person"]);
});

it("should extract type referenced as array in union property", () => {
const source = `
export interface Superhero {
sidekicks: Person[] | null,
}`;

const result = extractNames(source);
expect(result).toEqual(["Superhero", "Person"]);
});

it("should extract nested type reference", () => {
const source = `
export interface Superhero {
Expand Down Expand Up @@ -182,6 +192,17 @@ describe("traverseTypes", () => {
expect(result).toEqual(["Person", "SuperHero", "Villain"]);
});

it("should extract types from Tuple", () => {
const source = `
export interface Person {
id: number,
t: [SuperHero, Villain]
}`;

const result = extractNames(source);
expect(result).toEqual(["Person", "SuperHero", "Villain"]);
});

it("should extract type from type alias", () => {
const source = `
export type Person = SuperHero `;
Expand Down Expand Up @@ -293,6 +314,30 @@ describe("traverseTypes", () => {
const result = extractNames(source);
expect(result).toEqual(["Person", "Villain", "SuperHero"]);
});

it("should extract types from a very weird type definition (testing edge cases)", () => {
const source = `
export type Person = {
type: (SuperHero | Person2) & (SuperHero2 & Villain2) | SuperHero3[] | Villain3
tupleProp: [A | B, C & D]
} | Villain`;

const result = extractNames(source);
expect(result).toEqual([
"Person",
"SuperHero",
"Person2",
"SuperHero2",
"Villain2",
"SuperHero3",
"Villain3",
"A",
"B",
"C",
"D",
"Villain",
]);
});
});
});

Expand Down
8 changes: 3 additions & 5 deletions src/utils/traverseTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,13 @@ export function getExtractedTypeNames(
handleTypeNode(typeNode.elementType);
} else if (ts.isTypeLiteralNode(typeNode)) {
typeNode.forEachChild(visitorExtract);
} else if (ts.isTupleTypeNode(typeNode)) {
typeNode.elements.forEach(handleTypeNode);
} else if (
ts.isIntersectionTypeNode(typeNode) ||
ts.isUnionTypeNode(typeNode)
) {
typeNode.types.forEach((childNode: ts.TypeNode) => {
if (ts.isTypeReferenceNode(childNode)) {
handleTypeReferenceNode(childNode);
} else childNode.forEachChild(visitorExtract);
});
typeNode.types.forEach(handleTypeNode);
}
};

Expand Down

0 comments on commit b797dd0

Please sign in to comment.