Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make isFalsyType() return true for 0n #545

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/types/utilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,9 @@ describe("isFalsyType", () => {
[true, "false"],
[true, "0"],
[true, "null"],
[true, "0n"],
[true, "-0n"],
[false, "24n"],
])("returns %j when given %s", (expected, source) => {
const { sourceFile, typeChecker } = createSourceFileAndTypeChecker(`
${source};
Expand Down
30 changes: 28 additions & 2 deletions src/types/utilities.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Code largely based on https://github.com/ajafff/tsutils
// Original license: https://github.com/ajafff/tsutils/blob/26b195358ec36d59f00333115aa3ffd9611ca78b/LICENSE

import semver from "semver";
import ts from "typescript";

import {
Expand Down Expand Up @@ -46,8 +47,12 @@ export function isFalsyType(type: ts.Type): boolean {
return true;
}

if (type.isLiteral()) {
return !type.value;
if (typeIsLiteral(type)) {
if (typeof type.value === "object") {
return type.value.base10Value === "0";
} else {
return !type.value;
}
}

return isFalseLiteralType(type);
Expand Down Expand Up @@ -397,3 +402,24 @@ export function symbolHasReadonlyDeclaration(
export function unionTypeParts(type: ts.Type): ts.Type[] {
return isUnionType(type) ? type.types : [type];
}

/**
* TS's `type.isLiteral()` is bugged before TS v5.0 and won't return `true` for
* bigint literals. Use this function instead if you need to check for bigint
* literals in TS versions before v5.0. Otherwise, you should just use
* `type.isLiteral()`.
*
* See https://github.com/microsoft/TypeScript/pull/50929
*/
export function typeIsLiteral(type: ts.Type): type is ts.LiteralType {
if (semver.lt(ts.version, "5.0.0")) {
return isTypeFlagSet(
type,
ts.TypeFlags.StringLiteral |
ts.TypeFlags.NumberLiteral |
ts.TypeFlags.BigIntLiteral,
);
} else {
return type.isLiteral();
}
}
Loading