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 FP S4323 (use-type-alias): Ignore nullable types #4543

Merged
merged 2 commits into from Feb 1, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 0 additions & 5 deletions its/ruling/src/test/expected/jsts/eigen/typescript-S4323.json

This file was deleted.

@@ -1,11 +1,5 @@
{
"postgraphql:src/interface/type/NullableType.ts": [
34
],
"postgraphql:src/postgraphql/postgraphql.ts": [
37
],
"postgraphql:src/postgres/inventory/type/PgNullableType.ts": [
5
]
}
47 changes: 32 additions & 15 deletions packages/jsts/src/rules/S4323/rule.ts
Expand Up @@ -59,23 +59,40 @@ export const rule: Rule.RuleModule = {
const declaration = ancestors.find(
ancestor => (ancestor as TSESTree.Node).type === 'TSTypeAliasDeclaration',
);
if (!declaration) {
const composite = node as unknown as TSESTree.TSUnionType | TSESTree.TSIntersectionType;
if (composite.types.length > TYPE_THRESHOLD) {
const text = composite.types
.map(typeNode => context.sourceCode.getText(typeNode as unknown as estree.Node))
.sort((a, b) => a.localeCompare(b))
.join('|');
let occurrences = usage.get(text);
if (!occurrences) {
occurrences = [composite];
usage.set(text, occurrences);
} else {
occurrences.push(composite);
}
}
if (declaration) {
return;
}

const composite = node as unknown as TSESTree.TSUnionType | TSESTree.TSIntersectionType;
if (composite.types.length <= TYPE_THRESHOLD) {
return;
}

if (isNullableType(composite)) {
return;
}

const text = composite.types
.map(typeNode => context.sourceCode.getText(typeNode as unknown as estree.Node))
.sort((a, b) => a.localeCompare(b))
.join('|');
let occurrences = usage.get(text);
if (!occurrences) {
occurrences = [composite];
usage.set(text, occurrences);
} else {
occurrences.push(composite);
}
},
};

function isNullableType(node: TSESTree.TSUnionType | TSESTree.TSIntersectionType) {
return (
node.type === 'TSUnionType' &&
node.types.filter(
type => type.type !== 'TSNullKeyword' && type.type !== 'TSUndefinedKeyword',
).length === 1
);
}
},
};
6 changes: 6 additions & 0 deletions packages/jsts/src/rules/S4323/unit.test.ts
Expand Up @@ -71,6 +71,12 @@ ruleTester.run('Type aliases should be used', rule, {
let y: number | string | undefined;
let z: number | String | undefined; // this fine because case-sensitive`,
},
{
code: `
let x: T | null | undefined;
let y: T | null | undefined;
let z: T | null | undefined; `,
},
],
invalid: [
{
Expand Down