Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Show file tree
Hide file tree
Changes fromall 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 deletionspackages/eslint-plugin/src/rules/no-unnecessary-condition.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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)) {
returnBigInt((type.value.negative ? '-' : '') + type.value.base10Value);
returnpseudoBigIntToBigInt(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 DownExpand 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
MemberAuthor

@kirkwaiblingerkirkwaiblingerOct 22, 2024
edited
Loading

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 thevoid check.

  1. It is not tested for
  2. We've gone towards thinking ofvoid asunknown in terms of its possible values, rather thanundefined 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

JoshuaKGoldberg reacted with thumbs up emoji
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 DownExpand 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,bothsides of theexpression areliteralvalues.',
'Unnecessary conditional,comparison is always {{trueOrFalse}}. Bothsides of thecomparison always have aliteraltype.',
never: 'Unnecessary conditional, value is `never`.',
neverNullish:
'Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined.',
Expand DownExpand 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

[8]ページ先頭

©2009-2025 Movatter.jp