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

Skip to content
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
36 changes: 22 additions & 14 deletions packages/eslint-plugin/src/rules/no-unsafe-enum-comparison.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,33 @@ function typeViolates(leftTypeParts: ts.Type[], rightType: ts.Type): boolean {
}

function isNumberLike(type: ts.Type): boolean {
const typeParts = tsutils.intersectionConstituents(type);

return typeParts.some(typePart => {
return tsutils.isTypeFlagSet(
typePart,
ts.TypeFlags.Number | ts.TypeFlags.NumberLike,
return tsutils
.unionConstituents(type)
.every(unionPart =>
tsutils
.intersectionConstituents(unionPart)
.some(intersectionPart =>
tsutils.isTypeFlagSet(
intersectionPart,
ts.TypeFlags.Number | ts.TypeFlags.NumberLike,
),
),
);
});
}

function isStringLike(type: ts.Type): boolean {
const typeParts = tsutils.intersectionConstituents(type);

return typeParts.some(typePart => {
return tsutils.isTypeFlagSet(
typePart,
ts.TypeFlags.String | ts.TypeFlags.StringLike,
return tsutils
.unionConstituents(type)
.every(unionPart =>
tsutils
.intersectionConstituents(unionPart)
.some(intersectionPart =>
tsutils.isTypeFlagSet(
intersectionPart,
ts.TypeFlags.String | ts.TypeFlags.StringLike,
),
),
);
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1165,5 +1165,81 @@ ruleTester.run('no-unsafe-enum-comparison', rule, {
`,
errors: [{ messageId: 'mismatchedCondition' }],
},
{
code: `
enum NUMBER_ENUM {
First = 0,
Second = 1,
}

type NumberUnion = 0 | 1;

declare const numberUnion: NumberUnion;

switch (numberUnion) {
case NUMBER_ENUM.First:
case NUMBER_ENUM.Second:
break;
}
`,
errors: [
{
line: 12,
messageId: 'mismatchedCase',
},
{
line: 13,
messageId: 'mismatchedCase',
},
],
},
{
code: `
enum STRING_ENUM {
First = 'one',
Second = 'two',
}

type StringUnion = 'one' | 'two';

declare const stringUnion: StringUnion;

switch (stringUnion) {
case STRING_ENUM.First:
case STRING_ENUM.Second:
break;
}
`,
errors: [
{
line: 12,
messageId: 'mismatchedCase',
},
{
line: 13,
messageId: 'mismatchedCase',
},
],
},
{
code: `
declare const stringUnion: 'foo' | 'bar';

enum StringEnum {
FOO = 'foo',
BAR = 'bar',
}

declare const stringEnum: StringEnum;

stringUnion === stringEnum;
`,
errors: [
{
line: 11,
messageId: 'mismatchedCondition',
},
],
},
],
});
Loading