Skip to content

Commit

Permalink
fix: Normalize unions
Browse files Browse the repository at this point in the history
Closes #571.
  • Loading branch information
Gerrit0 committed Dec 27, 2020
1 parent 33c2bc6 commit 9f8375d
Show file tree
Hide file tree
Showing 3 changed files with 156 additions and 86 deletions.
21 changes: 21 additions & 0 deletions src/lib/models/types/union.ts
@@ -1,4 +1,6 @@
import { Type } from "./abstract";
import { IntrinsicType } from "./intrinsic";
import { LiteralType } from "./literal";

/**
* Represents an union type.
Expand Down Expand Up @@ -26,6 +28,7 @@ export class UnionType extends Type {
constructor(types: Type[]) {
super();
this.types = types;
this.normalize();
}

/**
Expand Down Expand Up @@ -61,4 +64,22 @@ export class UnionType extends Type {

return names.join(" | ");
}

private normalize() {
const trueIndex = this.types.findIndex((t) =>
t.equals(new LiteralType(true))
);
const falseIndex = this.types.findIndex((t) =>
t.equals(new LiteralType(false))
);

if (trueIndex !== -1 && falseIndex !== -1) {
this.types.splice(Math.max(trueIndex, falseIndex), 1);
this.types.splice(
Math.min(trueIndex, falseIndex),
1,
new IntrinsicType("boolean")
);
}
}
}
6 changes: 6 additions & 0 deletions src/test/converter/function/function.ts
Expand Up @@ -198,3 +198,9 @@ export const all: {
<T>(fn: (item: T) => boolean, iterator: Iterable<T>): boolean;
<T>(fn: (item: T) => boolean): (iterator: Iterable<T>) => boolean;
} = () => false as any;

export function boolOrUndef(x: number) {
if (x < 5) return true;
if (x > 20) return false;
return undefined;
}

0 comments on commit 9f8375d

Please sign in to comment.