Thanks to visit codestin.com
Credit goes to github.com

Skip to content

fix(eslint-plugin): [no-unnecessary-condition] improve error message for literal comparisons #10194

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

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
131 changes: 103 additions & 28 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ const valueIsPseudoBigInt = (
return typeof value === 'object';
};

const getValue = (type: ts.LiteralType): bigint | number | string => {
const getValueOfLiteralType = (
type: ts.LiteralType,
): bigint | number | string => {
if (valueIsPseudoBigInt(type.value)) {
return BigInt((type.value.negative ? '-' : '') + type.value.base10Value);
return pseudoBigIntToBigInt(type.value);
}
return type.value;
};
Expand All @@ -43,13 +45,12 @@ const isFalsyBigInt = (type: ts.Type): boolean => {
return (
tsutils.isLiteralType(type) &&
valueIsPseudoBigInt(type.value) &&
!getValue(type)
!getValueOfLiteralType(type)
);
};
const isTruthyLiteral = (type: ts.Type): boolean =>
tsutils.isTrueLiteralType(type) ||
// || type.
(type.isLiteral() && !!getValue(type));
(type.isLiteral() && !!getValueOfLiteralType(type));

const isPossiblyFalsy = (type: ts.Type): boolean =>
tsutils
Expand Down Expand Up @@ -89,13 +90,83 @@ const isPossiblyNullish = (type: ts.Type): boolean =>
const isAlwaysNullish = (type: ts.Type): boolean =>
tsutils.unionTypeParts(type).every(isNullishType);

// isLiteralType only covers numbers and strings, this is a more exhaustive check.
const isLiteral = (type: ts.Type): boolean =>
tsutils.isBooleanLiteralType(type) ||
type.flags === ts.TypeFlags.Undefined ||
type.flags === ts.TypeFlags.Null ||
type.flags === ts.TypeFlags.Void ||
Copy link
Member Author

@kirkwaiblinger kirkwaiblinger Oct 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that I intentionally omitted the void check.

  1. It is not tested for
  2. We've gone towards thinking of void as unknown in terms of its possible values, rather than undefined only. And if it doesn't have a specific, knowable value such that we can precompute the condition... then it's an indication that we can't in good faith tell the user the condition is unnecessary due to both sides of the condition being known literal values.
  3. Also I think TS bans most relevant usages of it anyways

type.isLiteral();
function toStaticValue(
type: ts.Type,
):
| { value: bigint | boolean | number | string | null | undefined }
| undefined {
// type.isLiteral() only covers numbers/bigints and strings, hence the rest of the branches.
if (tsutils.isBooleanLiteralType(type)) {
// Using `type.intrinsicName` instead of `type.value` because `type.value`
// is `undefined`, contrary to what the type guard tells us.
// See https://github.com/JoshuaKGoldberg/ts-api-utils/issues/528
return { value: type.intrinsicName === 'true' };
}
if (type.flags === ts.TypeFlags.Undefined) {
return { value: undefined };
}
if (type.flags === ts.TypeFlags.Null) {
return { value: null };
}
if (type.isLiteral()) {
return { value: getValueOfLiteralType(type) };
}

return undefined;
}

function pseudoBigIntToBigInt(value: ts.PseudoBigInt): bigint {
return BigInt((value.negative ? '-' : '') + value.base10Value);
}

const BOOL_OPERATORS = new Set([
'<',
'>',
'<=',
'>=',
'==',
'===',
'!=',
'!==',
] as const);

type BoolOperator = typeof BOOL_OPERATORS extends Set<infer T> ? T : never;

function isBoolOperator(operator: string): operator is BoolOperator {
return (BOOL_OPERATORS as Set<string>).has(operator);
}

function booleanComparison(
left: unknown,
operator: BoolOperator,
right: unknown,
): boolean {
switch (operator) {
case '!=':
// eslint-disable-next-line eqeqeq -- intentionally comparing with loose equality
return left != right;
case '!==':
return left !== right;
case '<':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left < right;
case '<=':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left <= right;
case '==':
// eslint-disable-next-line eqeqeq -- intentionally comparing with loose equality
return left == right;
case '===':
return left === right;
case '>':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left > right;
case '>=':
// @ts-expect-error: we don't care if the comparison seems unintentional.
return left >= right;
}
}

// #endregion

export type Options = [
Expand Down Expand Up @@ -141,7 +212,7 @@ export default createRule<Options, MessageId>({
alwaysTruthyFunc:
'This callback should return a conditional, but return is always truthy.',
literalBooleanExpression:
'Unnecessary conditional, both sides of the expression are literal values.',
'Unnecessary conditional, comparison is always {{trueOrFalse}}. Both sides of the comparison always have a literal type.',
never: 'Unnecessary conditional, value is `never`.',
neverNullish:
'Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined.',
Expand Down Expand Up @@ -397,19 +468,6 @@ export default createRule<Options, MessageId>({
* - https://github.com/microsoft/TypeScript/issues/32627
* - https://github.com/microsoft/TypeScript/issues/37160 (handled)
*/
const BOOL_OPERATORS = new Set([
'<',
'>',
'<=',
'>=',
'==',
'===',
'!=',
'!==',
] as const);
type BoolOperator = Parameters<typeof BOOL_OPERATORS.has>[0];
const isBoolOperator = (operator: string): operator is BoolOperator =>
(BOOL_OPERATORS as Set<string>).has(operator);
function checkIfBoolExpressionIsNecessaryConditional(
node: TSESTree.Node,
left: TSESTree.Node,
Expand All @@ -418,10 +476,27 @@ export default createRule<Options, MessageId>({
): void {
const leftType = getConstrainedTypeAtLocation(services, left);
const rightType = getConstrainedTypeAtLocation(services, right);
if (isLiteral(leftType) && isLiteral(rightType)) {
context.report({ node, messageId: 'literalBooleanExpression' });

const leftStaticValue = toStaticValue(leftType);
const rightStaticValue = toStaticValue(rightType);

if (leftStaticValue != null && rightStaticValue != null) {
const conditionIsTrue = booleanComparison(
leftStaticValue.value,
operator,
rightStaticValue.value,
);

context.report({
node,
messageId: 'literalBooleanExpression',
data: {
trueOrFalse: conditionIsTrue ? 'true' : 'false',
},
});
return;
}

// Workaround for https://github.com/microsoft/TypeScript/issues/37160
if (isStrictNullChecks) {
const UNDEFINED = ts.TypeFlags.Undefined;
Expand Down
Loading
Loading