From a0c828559187d1e167f2e095b503c887db4d4352 Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Thu, 27 Oct 2022 01:02:45 -0400 Subject: [PATCH 1/7] feat(eslint-plugin) [sort-type-union-intersection-members] rename to sort-type-constituents (#5879) * feat(eslint-plugin) [sort-type-union-intersection-members] rename to sort-type-constituents * Sigh, test rename * Added back rule, with replacedBy * Fixed up rules exports --- .eslintrc.js | 2 +- .../docs/rules/sort-type-constituents.md | 101 ++++++ .../sort-type-union-intersection-members.md | 5 + packages/eslint-plugin/src/configs/all.ts | 2 +- packages/eslint-plugin/src/rules/index.ts | 2 + .../src/rules/sort-type-constituents.ts | 269 ++++++++++++++ .../sort-type-union-intersection-members.ts | 2 + .../rules/sort-type-constituents.test.ts | 334 ++++++++++++++++++ 8 files changed, 715 insertions(+), 2 deletions(-) create mode 100644 packages/eslint-plugin/docs/rules/sort-type-constituents.md create mode 100644 packages/eslint-plugin/src/rules/sort-type-constituents.ts create mode 100644 packages/eslint-plugin/tests/rules/sort-type-constituents.test.ts diff --git a/.eslintrc.js b/.eslintrc.js index 8e62b6d06e3..da7ff36fd3b 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -308,7 +308,7 @@ module.exports = { rules: { // disallow ALL unused vars '@typescript-eslint/no-unused-vars': 'error', - '@typescript-eslint/sort-type-union-intersection-members': 'error', + '@typescript-eslint/sort-type-constituents': 'error', }, }, { diff --git a/packages/eslint-plugin/docs/rules/sort-type-constituents.md b/packages/eslint-plugin/docs/rules/sort-type-constituents.md new file mode 100644 index 00000000000..264ef2b52df --- /dev/null +++ b/packages/eslint-plugin/docs/rules/sort-type-constituents.md @@ -0,0 +1,101 @@ +--- +description: 'Enforce constituents of a type union/intersection to be sorted alphabetically.' +--- + +> 🛑 This file is source code, not the primary documentation location! 🛑 +> +> See **https://typescript-eslint.io/rules/sort-type-constituents** for documentation. + +Sorting union (`|`) and intersection (`&`) types can help: + +- keep your codebase standardized +- find repeated types +- reduce diff churn + +This rule reports on any types that aren't sorted alphabetically. + +> Types are sorted case-insensitively and treating numbers like a human would, falling back to character code sorting in case of ties. + +## Examples + + + +### ❌ Incorrect + +```ts +type T1 = B | A; + +type T2 = { b: string } & { a: string }; + +type T3 = [1, 2, 4] & [1, 2, 3]; + +type T4 = + | [1, 2, 4] + | [1, 2, 3] + | { b: string } + | { a: string } + | (() => void) + | (() => string) + | 'b' + | 'a' + | 'b' + | 'a' + | readonly string[] + | readonly number[] + | string[] + | number[] + | B + | A + | string + | any; +``` + +### ✅ Correct + +```ts +type T1 = A | B; + +type T2 = { a: string } & { b: string }; + +type T3 = [1, 2, 3] & [1, 2, 4]; + +type T4 = + | any + | string + | A + | B + | number[] + | string[] + | readonly number[] + | readonly string[] + | 'a' + | 'b' + | 'a' + | 'b' + | (() => string) + | (() => void) + | { a: string } + | { b: string } + | [1, 2, 3] + | [1, 2, 4]; +``` + +## Options + +### `groupOrder` + +Each constituent of the type is placed into a group, and then the rule sorts alphabetically within each group. +The ordering of groups is determined by this option. + +- `conditional` - Conditional types (`A extends B ? C : D`) +- `function` - Function and constructor types (`() => void`, `new () => type`) +- `import` - Import types (`import('path')`) +- `intersection` - Intersection types (`A & B`) +- `keyword` - Keyword types (`any`, `string`, etc) +- `literal` - Literal types (`1`, `'b'`, `true`, etc) +- `named` - Named types (`A`, `A['prop']`, `B[]`, `Array`) +- `object` - Object types (`{ a: string }`, `{ [key: string]: number }`) +- `operator` - Operator types (`keyof A`, `typeof B`, `readonly C[]`) +- `tuple` - Tuple types (`[A, B, C]`) +- `union` - Union types (`A | B`) +- `nullish` - `null` and `undefined` diff --git a/packages/eslint-plugin/docs/rules/sort-type-union-intersection-members.md b/packages/eslint-plugin/docs/rules/sort-type-union-intersection-members.md index 2a47547219b..dbaf1807edf 100644 --- a/packages/eslint-plugin/docs/rules/sort-type-union-intersection-members.md +++ b/packages/eslint-plugin/docs/rules/sort-type-union-intersection-members.md @@ -6,6 +6,11 @@ description: 'Enforce members of a type union/intersection to be sorted alphabet > > See **https://typescript-eslint.io/rules/sort-type-union-intersection-members** for documentation. +:::danger Deprecated + +This rule has been renamed to [`sort-type-union-intersection-members`](./sort-type-union-intersection-members.md). +::: + Sorting union (`|`) and intersection (`&`) types can help: - keep your codebase standardized diff --git a/packages/eslint-plugin/src/configs/all.ts b/packages/eslint-plugin/src/configs/all.ts index 1f6530ead3e..20ea892f581 100644 --- a/packages/eslint-plugin/src/configs/all.ts +++ b/packages/eslint-plugin/src/configs/all.ts @@ -154,7 +154,7 @@ export = { '@typescript-eslint/return-await': 'error', semi: 'off', '@typescript-eslint/semi': 'error', - '@typescript-eslint/sort-type-union-intersection-members': 'error', + '@typescript-eslint/sort-type-constituents': 'error', 'space-before-blocks': 'off', '@typescript-eslint/space-before-blocks': 'error', 'space-before-function-paren': 'off', diff --git a/packages/eslint-plugin/src/rules/index.ts b/packages/eslint-plugin/src/rules/index.ts index 851661400fb..8a3c2bbf437 100644 --- a/packages/eslint-plugin/src/rules/index.ts +++ b/packages/eslint-plugin/src/rules/index.ts @@ -115,6 +115,7 @@ import restrictPlusOperands from './restrict-plus-operands'; import restrictTemplateExpressions from './restrict-template-expressions'; import returnAwait from './return-await'; import semi from './semi'; +import sortTypeConstituents from './sort-type-constituents'; import sortTypeUnionIntersectionMembers from './sort-type-union-intersection-members'; import spaceBeforeBlocks from './space-before-blocks'; import spaceBeforeFunctionParen from './space-before-function-paren'; @@ -245,6 +246,7 @@ export default { 'restrict-template-expressions': restrictTemplateExpressions, 'return-await': returnAwait, semi: semi, + 'sort-type-constituents': sortTypeConstituents, 'sort-type-union-intersection-members': sortTypeUnionIntersectionMembers, 'space-before-blocks': spaceBeforeBlocks, 'space-before-function-paren': spaceBeforeFunctionParen, diff --git a/packages/eslint-plugin/src/rules/sort-type-constituents.ts b/packages/eslint-plugin/src/rules/sort-type-constituents.ts new file mode 100644 index 00000000000..92b5e44c6f9 --- /dev/null +++ b/packages/eslint-plugin/src/rules/sort-type-constituents.ts @@ -0,0 +1,269 @@ +import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; +import { AST_NODE_TYPES } from '@typescript-eslint/utils'; + +import * as util from '../util'; +import { getEnumNames } from '../util'; + +enum Group { + conditional = 'conditional', + function = 'function', + import = 'import', + intersection = 'intersection', + keyword = 'keyword', + nullish = 'nullish', + literal = 'literal', + named = 'named', + object = 'object', + operator = 'operator', + tuple = 'tuple', + union = 'union', +} + +function getGroup(node: TSESTree.TypeNode): Group { + switch (node.type) { + case AST_NODE_TYPES.TSConditionalType: + return Group.conditional; + + case AST_NODE_TYPES.TSConstructorType: + case AST_NODE_TYPES.TSFunctionType: + return Group.function; + + case AST_NODE_TYPES.TSImportType: + return Group.import; + + case AST_NODE_TYPES.TSIntersectionType: + return Group.intersection; + + case AST_NODE_TYPES.TSAnyKeyword: + case AST_NODE_TYPES.TSBigIntKeyword: + case AST_NODE_TYPES.TSBooleanKeyword: + case AST_NODE_TYPES.TSNeverKeyword: + case AST_NODE_TYPES.TSNumberKeyword: + case AST_NODE_TYPES.TSObjectKeyword: + case AST_NODE_TYPES.TSStringKeyword: + case AST_NODE_TYPES.TSSymbolKeyword: + case AST_NODE_TYPES.TSThisType: + case AST_NODE_TYPES.TSUnknownKeyword: + case AST_NODE_TYPES.TSIntrinsicKeyword: + return Group.keyword; + + case AST_NODE_TYPES.TSNullKeyword: + case AST_NODE_TYPES.TSUndefinedKeyword: + case AST_NODE_TYPES.TSVoidKeyword: + return Group.nullish; + + case AST_NODE_TYPES.TSLiteralType: + case AST_NODE_TYPES.TSTemplateLiteralType: + return Group.literal; + + case AST_NODE_TYPES.TSArrayType: + case AST_NODE_TYPES.TSIndexedAccessType: + case AST_NODE_TYPES.TSInferType: + case AST_NODE_TYPES.TSTypeReference: + return Group.named; + + case AST_NODE_TYPES.TSMappedType: + case AST_NODE_TYPES.TSTypeLiteral: + return Group.object; + + case AST_NODE_TYPES.TSTypeOperator: + case AST_NODE_TYPES.TSTypeQuery: + return Group.operator; + + case AST_NODE_TYPES.TSTupleType: + return Group.tuple; + + case AST_NODE_TYPES.TSUnionType: + return Group.union; + + // These types should never occur as part of a union/intersection + case AST_NODE_TYPES.TSAbstractKeyword: + case AST_NODE_TYPES.TSAsyncKeyword: + case AST_NODE_TYPES.TSDeclareKeyword: + case AST_NODE_TYPES.TSExportKeyword: + case AST_NODE_TYPES.TSNamedTupleMember: + case AST_NODE_TYPES.TSOptionalType: + case AST_NODE_TYPES.TSPrivateKeyword: + case AST_NODE_TYPES.TSProtectedKeyword: + case AST_NODE_TYPES.TSPublicKeyword: + case AST_NODE_TYPES.TSReadonlyKeyword: + case AST_NODE_TYPES.TSRestType: + case AST_NODE_TYPES.TSStaticKeyword: + case AST_NODE_TYPES.TSTypePredicate: + /* istanbul ignore next */ + throw new Error(`Unexpected Type ${node.type}`); + } +} + +function requiresParentheses(node: TSESTree.TypeNode): boolean { + return ( + node.type === AST_NODE_TYPES.TSFunctionType || + node.type === AST_NODE_TYPES.TSConstructorType + ); +} + +export type Options = [ + { + checkIntersections?: boolean; + checkUnions?: boolean; + groupOrder?: string[]; + }, +]; +export type MessageIds = 'notSorted' | 'notSortedNamed' | 'suggestFix'; + +export default util.createRule({ + name: 'sort-type-constituents', + meta: { + type: 'suggestion', + docs: { + description: + 'Enforce constituents of a type union/intersection to be sorted alphabetically', + recommended: false, + }, + fixable: 'code', + hasSuggestions: true, + messages: { + notSorted: '{{type}} type constituents must be sorted.', + notSortedNamed: '{{type}} type {{name}} constituents must be sorted.', + suggestFix: 'Sort constituents of type (removes all comments).', + }, + schema: [ + { + type: 'object', + properties: { + checkIntersections: { + description: 'Whether to check intersection types.', + type: 'boolean', + }, + checkUnions: { + description: 'Whether to check union types.', + type: 'boolean', + }, + groupOrder: { + description: 'Ordering of the groups.', + type: 'array', + items: { + type: 'string', + enum: getEnumNames(Group), + }, + }, + }, + }, + ], + }, + defaultOptions: [ + { + checkIntersections: true, + checkUnions: true, + groupOrder: [ + Group.named, + Group.keyword, + Group.operator, + Group.literal, + Group.function, + Group.import, + Group.conditional, + Group.object, + Group.tuple, + Group.intersection, + Group.union, + Group.nullish, + ], + }, + ], + create(context, [{ checkIntersections, checkUnions, groupOrder }]) { + const sourceCode = context.getSourceCode(); + + const collator = new Intl.Collator('en', { + sensitivity: 'base', + numeric: true, + }); + + function checkSorting( + node: TSESTree.TSIntersectionType | TSESTree.TSUnionType, + ): void { + const sourceOrder = node.types.map(type => { + const group = groupOrder?.indexOf(getGroup(type)) ?? -1; + return { + group: group === -1 ? Number.MAX_SAFE_INTEGER : group, + node: type, + text: sourceCode.getText(type), + }; + }); + const expectedOrder = [...sourceOrder].sort((a, b) => { + if (a.group !== b.group) { + return a.group - b.group; + } + + return ( + collator.compare(a.text, b.text) || + (a.text < b.text ? -1 : a.text > b.text ? 1 : 0) + ); + }); + + const hasComments = node.types.some(type => { + const count = + sourceCode.getCommentsBefore(type).length + + sourceCode.getCommentsAfter(type).length; + return count > 0; + }); + + for (let i = 0; i < expectedOrder.length; i += 1) { + if (expectedOrder[i].node !== sourceOrder[i].node) { + let messageId: MessageIds = 'notSorted'; + const data = { + name: '', + type: + node.type === AST_NODE_TYPES.TSIntersectionType + ? 'Intersection' + : 'Union', + }; + if (node.parent?.type === AST_NODE_TYPES.TSTypeAliasDeclaration) { + messageId = 'notSortedNamed'; + data.name = node.parent.id.name; + } + + const fix: TSESLint.ReportFixFunction = fixer => { + const sorted = expectedOrder + .map(t => (requiresParentheses(t.node) ? `(${t.text})` : t.text)) + .join( + node.type === AST_NODE_TYPES.TSIntersectionType ? ' & ' : ' | ', + ); + + return fixer.replaceText(node, sorted); + }; + return context.report({ + node, + messageId, + data, + // don't autofix if any of the types have leading/trailing comments + // the logic for preserving them correctly is a pain - we may implement this later + ...(hasComments + ? { + suggest: [ + { + messageId: 'suggestFix', + fix, + }, + ], + } + : { fix }), + }); + } + } + } + + return { + ...(checkIntersections && { + TSIntersectionType(node): void { + checkSorting(node); + }, + }), + ...(checkUnions && { + TSUnionType(node): void { + checkSorting(node); + }, + }), + }; + }, +}); diff --git a/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts b/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts index ded7212c6c9..2a83b4b0525 100644 --- a/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts +++ b/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts @@ -114,6 +114,7 @@ export type MessageIds = 'notSorted' | 'notSortedNamed' | 'suggestFix'; export default util.createRule({ name: 'sort-type-union-intersection-members', meta: { + deprecated: true, type: 'suggestion', docs: { description: @@ -127,6 +128,7 @@ export default util.createRule({ notSortedNamed: '{{type}} type {{name}} members must be sorted.', suggestFix: 'Sort members of type (removes all comments).', }, + replacedBy: ['@typescript-eslint/sort-type-constituents'], schema: [ { type: 'object', diff --git a/packages/eslint-plugin/tests/rules/sort-type-constituents.test.ts b/packages/eslint-plugin/tests/rules/sort-type-constituents.test.ts new file mode 100644 index 00000000000..b9989c2cf87 --- /dev/null +++ b/packages/eslint-plugin/tests/rules/sort-type-constituents.test.ts @@ -0,0 +1,334 @@ +import type { TSESLint } from '@typescript-eslint/utils'; + +import type { + MessageIds, + Options, +} from '../../src/rules/sort-type-constituents'; +import rule from '../../src/rules/sort-type-constituents'; +import { noFormat, RuleTester } from '../RuleTester'; + +const ruleTester = new RuleTester({ + parser: '@typescript-eslint/parser', +}); + +const valid = (operator: '|' | '&'): TSESLint.ValidTestCase[] => [ + { + code: `type T = A ${operator} B;`, + }, + { + code: `type T = A ${operator} /* comment */ B;`, + }, + { + code: `type T = 'A' ${operator} 'B';`, + }, + { + code: `type T = 1 ${operator} 2;`, + }, + { + code: noFormat`type T = (A) ${operator} (B);`, + }, + { + code: `type T = { a: string } ${operator} { b: string };`, + }, + { + code: `type T = [1, 2, 3] ${operator} [1, 2, 4];`, + }, + { + code: `type T = (() => string) ${operator} (() => void);`, + }, + { + code: `type T = () => string ${operator} void;`, + }, + { + // testing the default ordering + code: noFormat` +type T = + ${operator} A + ${operator} B + ${operator} intrinsic + ${operator} number[] + ${operator} string[] + ${operator} any + ${operator} string + ${operator} symbol + ${operator} this + ${operator} readonly number[] + ${operator} readonly string[] + ${operator} 'a' + ${operator} 'b' + ${operator} "a" + ${operator} "b" + ${operator} (() => string) + ${operator} (() => void) + ${operator} (new () => string) + ${operator} (new () => void) + ${operator} import('bar') + ${operator} import('foo') + ${operator} (number extends string ? unknown : never) + ${operator} (string extends string ? unknown : never) + ${operator} { [a in string]: string } + ${operator} { [a: string]: string } + ${operator} { [b in string]: string } + ${operator} { [b: string]: string } + ${operator} { a: string } + ${operator} { b: string } + ${operator} [1, 2, 3] + ${operator} [1, 2, 4] + ${operator} (A & B) + ${operator} (B & C) + ${operator} (A | B) + ${operator} (B | C) + ${operator} null + ${operator} undefined + `, + }, +]; +const invalid = ( + operator: '|' | '&', +): TSESLint.InvalidTestCase[] => { + const type = operator === '|' ? 'Union' : 'Intersection'; + return [ + { + code: `type T = B ${operator} A;`, + output: `type T = A ${operator} B;`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = 'B' ${operator} 'A';`, + output: `type T = 'A' ${operator} 'B';`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = 2 ${operator} 1;`, + output: `type T = 1 ${operator} 2;`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: noFormat`type T = (B) ${operator} (A);`, + output: `type T = A ${operator} B;`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = { b: string } ${operator} { a: string };`, + output: `type T = { a: string } ${operator} { b: string };`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = [1, 2, 4] ${operator} [1, 2, 3];`, + output: `type T = [1, 2, 3] ${operator} [1, 2, 4];`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = (() => void) ${operator} (() => string);`, + output: `type T = (() => string) ${operator} (() => void);`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = () => void ${operator} string;`, + output: `type T = () => string ${operator} void;`, + errors: [ + { + messageId: 'notSorted', + data: { + type, + }, + }, + ], + }, + { + code: `type T = () => undefined ${operator} null;`, + output: `type T = () => null ${operator} undefined;`, + errors: [ + { + messageId: 'notSorted', + data: { + type, + }, + }, + ], + }, + { + code: noFormat` +type T = + ${operator} [1, 2, 4] + ${operator} [1, 2, 3] + ${operator} { b: string } + ${operator} { a: string } + ${operator} (() => void) + ${operator} (() => string) + ${operator} "b" + ${operator} "a" + ${operator} 'b' + ${operator} 'a' + ${operator} readonly string[] + ${operator} readonly number[] + ${operator} string[] + ${operator} number[] + ${operator} B + ${operator} A + ${operator} undefined + ${operator} null + ${operator} string + ${operator} any; + `, + output: ` +type T = + A ${operator} B ${operator} number[] ${operator} string[] ${operator} any ${operator} string ${operator} readonly number[] ${operator} readonly string[] ${operator} 'a' ${operator} 'b' ${operator} "a" ${operator} "b" ${operator} (() => string) ${operator} (() => void) ${operator} { a: string } ${operator} { b: string } ${operator} [1, 2, 3] ${operator} [1, 2, 4] ${operator} null ${operator} undefined; + `, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + }, + ], + }, + { + code: `type T = B ${operator} /* comment */ A;`, + output: null, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + suggestions: [ + { + messageId: 'suggestFix', + output: `type T = A ${operator} B;`, + }, + ], + }, + ], + }, + { + code: `type T = (() => /* comment */ A) ${operator} B;`, + output: `type T = B ${operator} (() => /* comment */ A);`, + errors: [ + { + messageId: 'notSortedNamed', + data: { + type, + name: 'T', + }, + suggestions: null, + }, + ], + }, + { + code: `type Expected = (new (x: number) => boolean) ${operator} string;`, + output: `type Expected = string ${operator} (new (x: number) => boolean);`, + errors: [ + { + messageId: 'notSortedNamed', + }, + ], + }, + ]; +}; + +ruleTester.run('sort-type-constituents', rule, { + valid: [ + ...valid('|'), + { + code: 'type T = B | A;', + options: [ + { + checkUnions: false, + }, + ], + }, + + ...valid('&'), + { + code: 'type T = B & A;', + options: [ + { + checkIntersections: false, + }, + ], + }, + + { + code: noFormat` +type T = [1] | 'a' | 'b' | "b" | 1 | 2 | {}; + `, + options: [ + { + groupOrder: ['tuple', 'literal', 'object'], + }, + ], + }, + { + // if not specified - groups should be placed last + code: ` +type T = 1 | string | {} | A; + `, + options: [ + { + groupOrder: ['literal', 'keyword'], + }, + ], + }, + ], + invalid: [...invalid('|'), ...invalid('&')], +}); From 344322add846d03c6c9981e486b09e6ba1196555 Mon Sep 17 00:00:00 2001 From: Shogo Hida Date: Thu, 27 Oct 2022 14:12:13 +0900 Subject: [PATCH 2/7] fix(eslint-plugin): enable react/jsx-curly-brace-presence lint rule in website package (#5894) Add 'react/jsx-curly-brace-presence': 'error' Co-authored-by: Josh Goldberg --- packages/website/.eslintrc.js | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/website/.eslintrc.js b/packages/website/.eslintrc.js index 2359a5a4cd5..323ce34a38d 100644 --- a/packages/website/.eslintrc.js +++ b/packages/website/.eslintrc.js @@ -23,6 +23,7 @@ module.exports = { 'react/jsx-no-target-blank': 'off', 'react/no-unescaped-entities': 'off', '@typescript-eslint/internal/prefer-ast-types-enum': 'off', + 'react/jsx-curly-brace-presence': 'error', }, settings: { react: { From d806bda82343712a24e3c78b9b34d4345dd1de3b Mon Sep 17 00:00:00 2001 From: kmin-jeong <53456037+kmin-jeong@users.noreply.github.com> Date: Sat, 29 Oct 2022 21:45:53 +0900 Subject: [PATCH 3/7] feat(eslint-plugin): [no-invalid-void-type] better report message for void used as a constituent inside a function return type (#5274) * feat: update repository * remove duplicate examples * feat:add about re-exporting --isolatedModules in When Not To Use It * feat: add exmaples * fix: remove duplicate examples in correct * fix:correct words * fix: fix space-between * fix: fix code * fix: fix code space * fix: check error * fix:missed examples * feat: read review and fix them fix examples and --Isolatedmodules explain * feat: add two taps one is correct, another is incorrect * fix: add * feat: fix explaination about `isolatedmodules` * fix: fix explain about `isolatedModules` * fis: modify When no to use it * fix: revert change log * fix: add lint * fix: add lint * add: fix code * fix:fix docs splits * feat: add lint * Update packages/eslint-plugin/docs/rules/consistent-type-exports.md * feat:change error message better * fix:separating message and made types about union * fix: separate error message * fix:fix mistake type * fix:fix typo * fix:fix error message in case of union * fix:fix error message in InvalidVoidForUnion * fix: add logic about union * feat: add test case * Switched change to just enhance error message * oops comment Co-authored-by: Josh Goldberg Co-authored-by: Josh Goldberg --- .../src/rules/no-invalid-void-type.ts | 23 +++++++++++----- .../tests/rules/no-invalid-void-type.test.ts | 26 ++++++++++++++++--- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/packages/eslint-plugin/src/rules/no-invalid-void-type.ts b/packages/eslint-plugin/src/rules/no-invalid-void-type.ts index 7cda184e4fd..9f938ac438f 100644 --- a/packages/eslint-plugin/src/rules/no-invalid-void-type.ts +++ b/packages/eslint-plugin/src/rules/no-invalid-void-type.ts @@ -13,7 +13,8 @@ type MessageIds = | 'invalidVoidNotReturnOrGeneric' | 'invalidVoidNotReturn' | 'invalidVoidNotReturnOrThisParam' - | 'invalidVoidNotReturnOrThisParamOrGeneric'; + | 'invalidVoidNotReturnOrThisParamOrGeneric' + | 'invalidVoidUnionConstituent'; export default util.createRule<[Options], MessageIds>({ name: 'no-invalid-void-type', @@ -25,14 +26,16 @@ export default util.createRule<[Options], MessageIds>({ }, messages: { invalidVoidForGeneric: - '{{ generic }} may not have void as a type variable.', + '{{ generic }} may not have void as a type argument.', invalidVoidNotReturnOrGeneric: - 'void is only valid as a return type or generic type variable.', + 'void is only valid as a return type or generic type argument.', invalidVoidNotReturn: 'void is only valid as a return type.', invalidVoidNotReturnOrThisParam: 'void is only valid as return type or type of `this` parameter.', invalidVoidNotReturnOrThisParamOrGeneric: - 'void is only valid as a return type or generic type variable or the type of a `this` parameter.', + 'void is only valid as a return type or generic type argument or the type of a `this` parameter.', + invalidVoidUnionConstituent: + 'void is not valid as a constituent in a union type', }, schema: [ { @@ -136,7 +139,7 @@ export default util.createRule<[Options], MessageIds>({ ): void { if (parentNode.default !== node) { context.report({ - messageId: 'invalidVoidNotReturnOrGeneric', + messageId: getNotReturnOrGenericMessageId(node), node, }); } @@ -218,7 +221,7 @@ export default util.createRule<[Options], MessageIds>({ allowInGenericTypeArguments && allowAsThisParameter ? 'invalidVoidNotReturnOrThisParamOrGeneric' : allowInGenericTypeArguments - ? 'invalidVoidNotReturnOrGeneric' + ? getNotReturnOrGenericMessageId(node) : allowAsThisParameter ? 'invalidVoidNotReturnOrThisParam' : 'invalidVoidNotReturn', @@ -228,3 +231,11 @@ export default util.createRule<[Options], MessageIds>({ }; }, }); + +function getNotReturnOrGenericMessageId( + node: TSESTree.TSVoidKeyword, +): MessageIds { + return node.parent!.type === AST_NODE_TYPES.TSUnionType + ? 'invalidVoidUnionConstituent' + : 'invalidVoidNotReturnOrGeneric'; +} diff --git a/packages/eslint-plugin/tests/rules/no-invalid-void-type.test.ts b/packages/eslint-plugin/tests/rules/no-invalid-void-type.test.ts index 8164e85b2bd..1a972b665be 100644 --- a/packages/eslint-plugin/tests/rules/no-invalid-void-type.test.ts +++ b/packages/eslint-plugin/tests/rules/no-invalid-void-type.test.ts @@ -316,7 +316,7 @@ ruleTester.run('allowInGenericTypeArguments: true', rule, { code: 'type UnionType2 = string | number | void;', errors: [ { - messageId: 'invalidVoidNotReturnOrGeneric', + messageId: 'invalidVoidUnionConstituent', line: 1, column: 37, }, @@ -326,12 +326,32 @@ ruleTester.run('allowInGenericTypeArguments: true', rule, { code: 'type UnionType3 = string | ((number & any) | (string | void));', errors: [ { - messageId: 'invalidVoidNotReturnOrGeneric', + messageId: 'invalidVoidUnionConstituent', line: 1, column: 56, }, ], }, + { + code: 'declare function test(): number | void;', + errors: [ + { + messageId: 'invalidVoidUnionConstituent', + line: 1, + column: 35, + }, + ], + }, + { + code: 'declare function test(): T;', + errors: [ + { + messageId: 'invalidVoidUnionConstituent', + line: 1, + column: 42, + }, + ], + }, { code: 'type IntersectionType = string & number & void;', errors: [ @@ -394,7 +414,7 @@ ruleTester.run('allowInGenericTypeArguments: true', rule, { code: 'type invalidVoidUnion = void | Map;', errors: [ { - messageId: 'invalidVoidNotReturnOrGeneric', + messageId: 'invalidVoidUnionConstituent', line: 1, column: 25, }, From 891b0879ba9c64a4722b8c0bf9e599a725b6d6df Mon Sep 17 00:00:00 2001 From: Brad Zacher Date: Sat, 29 Oct 2022 06:25:11 -0700 Subject: [PATCH 4/7] fix(typescript-estree): don't allow single-run unless we're in type-aware linting mode (#5893) Co-authored-by: Josh Goldberg --- .../src/parseSettings/inferSingleRun.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/typescript-estree/src/parseSettings/inferSingleRun.ts b/packages/typescript-estree/src/parseSettings/inferSingleRun.ts index 723f857ece9..5d765a22ce9 100644 --- a/packages/typescript-estree/src/parseSettings/inferSingleRun.ts +++ b/packages/typescript-estree/src/parseSettings/inferSingleRun.ts @@ -15,6 +15,16 @@ import type { TSESTreeOptions } from '../parser-options'; * @returns Whether this is part of a single run, rather than a long-running process. */ export function inferSingleRun(options: TSESTreeOptions | undefined): boolean { + if ( + // single-run implies type-aware linting - no projects means we can't be in single-run mode + options?.project == null || + // programs passed via options means the user should be managing the programs, so we shouldn't + // be creating our own single-run programs accidentally + options?.programs != null + ) { + return false; + } + // Allow users to explicitly inform us of their intent to perform a single run (or not) with TSESTREE_SINGLE_RUN if (process.env.TSESTREE_SINGLE_RUN === 'false') { return false; From 8ed72192c274249d26628fb125796e71318b857a Mon Sep 17 00:00:00 2001 From: YeonJuan Date: Sun, 30 Oct 2022 12:25:18 +0900 Subject: [PATCH 5/7] fix(eslint-plugin): [no-extra-parens] handle type assertion in extends clause (#5901) * fix(eslint-plugin): [no-extra-parens] handle type assertion in extends clause * Add test cases * Handle class expression * Add test cases --- .../src/rules/no-extra-parens.ts | 26 +++++++++++++-- .../tests/rules/no-extra-parens.test.ts | 32 +++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/packages/eslint-plugin/src/rules/no-extra-parens.ts b/packages/eslint-plugin/src/rules/no-extra-parens.ts index 3a4a5973074..a44276a0a76 100644 --- a/packages/eslint-plugin/src/rules/no-extra-parens.ts +++ b/packages/eslint-plugin/src/rules/no-extra-parens.ts @@ -141,8 +141,30 @@ export default util.createRule({ }, BinaryExpression: binaryExp, CallExpression: callExp, - // ClassDeclaration - // ClassExpression + ClassDeclaration(node) { + if (node.superClass?.type === AST_NODE_TYPES.TSAsExpression) { + return rules.ClassDeclaration({ + ...node, + superClass: { + ...node.superClass, + type: AST_NODE_TYPES.SequenceExpression as any, + }, + }); + } + return rules.ClassDeclaration(node); + }, + ClassExpression(node) { + if (node.superClass?.type === AST_NODE_TYPES.TSAsExpression) { + return rules.ClassExpression({ + ...node, + superClass: { + ...node.superClass, + type: AST_NODE_TYPES.SequenceExpression as any, + }, + }); + } + return rules.ClassExpression(node); + }, ConditionalExpression(node) { // reduces the precedence of the node so the rule thinks it needs to be wrapped if (util.isTypeAssertion(node.test)) { diff --git a/packages/eslint-plugin/tests/rules/no-extra-parens.test.ts b/packages/eslint-plugin/tests/rules/no-extra-parens.test.ts index 6a9e87111aa..369f55101f2 100644 --- a/packages/eslint-plugin/tests/rules/no-extra-parens.test.ts +++ b/packages/eslint-plugin/tests/rules/no-extra-parens.test.ts @@ -141,6 +141,10 @@ t.true((me.get as SinonStub).calledWithExactly('/foo', other)); t.true((me.get).calledWithExactly('/foo', other)); (requestInit.headers as Headers).get('Cookie'); ( requestInit.headers).get('Cookie'); +class Foo {} +class Foo extends (Bar as any) {} +const foo = class {}; +const foo = class extends (Bar as any) {} `, parserOptions: { ecmaFeatures: { @@ -254,6 +258,10 @@ new a((1)); a<(A)>((1)); async function f(arg: Promise) { await (arg); } async function f(arg: any) { await ((arg as Promise)); } +class Foo extends ((Bar as any)) {} +class Foo extends (Bar) {} +const foo = class extends ((Bar as any)) {} +const foo = class extends (Bar) {} `, output: ` a = b * c; @@ -267,6 +275,10 @@ new a(1); a<(A)>(1); async function f(arg: Promise) { await arg; } async function f(arg: any) { await (arg as Promise); } +class Foo extends (Bar as any) {} +class Foo extends Bar {} +const foo = class extends (Bar as any) {} +const foo = class extends Bar {} `, errors: [ { @@ -324,6 +336,26 @@ async function f(arg: any) { await (arg as Promise); } line: 12, column: 37, }, + { + messageId: 'unexpected', + line: 13, + column: 20, + }, + { + messageId: 'unexpected', + line: 14, + column: 19, + }, + { + messageId: 'unexpected', + line: 15, + column: 28, + }, + { + messageId: 'unexpected', + line: 16, + column: 27, + }, ], }), ...batchedSingleLineTests({ From 54141946ac2a25799bb622d47d9a3fd1fb316ef9 Mon Sep 17 00:00:00 2001 From: "typescript-eslint[bot]" <53356952+typescript-eslint[bot]@users.noreply.github.com> Date: Sun, 30 Oct 2022 23:03:00 -0400 Subject: [PATCH 6/7] chore: update sponsors (#5905) Co-authored-by: typescript-eslint[bot] --- packages/website/data/sponsors.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/website/data/sponsors.json b/packages/website/data/sponsors.json index faef97d207f..a4aa0623e04 100644 --- a/packages/website/data/sponsors.json +++ b/packages/website/data/sponsors.json @@ -39,6 +39,14 @@ "totalDonations": 120000, "website": "https://blog.coinbase.com/engineering-and-security/home" }, + { + "id": "Sentry", + "image": "https://images.opencollective.com/sentry/9620d33/logo.png", + "name": "Sentry", + "tier": "sponsor", + "totalDonations": 114800, + "website": "https://sentry.io/welcome/" + }, { "id": "n8n.io - n8n GmbH", "image": "https://images.opencollective.com/n8n/dca2f0c/logo.png", @@ -79,14 +87,6 @@ "totalDonations": 54000, "website": "https://www.future-processing.com/" }, - { - "id": "Sentry", - "image": "https://images.opencollective.com/sentry/9620d33/logo.png", - "name": "Sentry", - "tier": "supporter", - "totalDonations": 50000, - "website": "https://sentry.io/welcome/" - }, { "id": "Whitebox", "image": "https://images.opencollective.com/whiteboxinc/ef0d11d/logo.png", From 1f14c03d2696ce02537c08aba683bdd587de5e6b Mon Sep 17 00:00:00 2001 From: Brad Zacher Date: Mon, 31 Oct 2022 03:53:04 -0700 Subject: [PATCH 7/7] docs(eslint-plugin): [consistent-type-imports] make a note about `parserOptions.emitDecoratorMetadata` (#5904) * docs(eslint-plugin): [consistent-type-imports] make a note about `parserOptions.emitDecoratorMetadata` * Update consistent-type-imports.md * Update consistent-type-imports.md * Update consistent-type-imports.md * Update consistent-type-imports.md --- .../eslint-plugin/docs/rules/consistent-type-imports.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/eslint-plugin/docs/rules/consistent-type-imports.md b/packages/eslint-plugin/docs/rules/consistent-type-imports.md index 6e6912d34cf..745930d0d54 100644 --- a/packages/eslint-plugin/docs/rules/consistent-type-imports.md +++ b/packages/eslint-plugin/docs/rules/consistent-type-imports.md @@ -48,6 +48,12 @@ type T = import('Foo').Foo; const x: import('Bar') = 1; ``` +## Usage with `emitDecoratorMetadata` + +The `emitDecoratorMetadata` compiler option changes the code the TypeScript emits. In short - it causes TypeScript to create references to value imports when they are used in a type-only location. If you are using `emitDecoratorMetadata` then our tooling will require additional information in order for the rule to work correctly. + +If you are using [type-aware linting](https://typescript-eslint.io/docs/linting/typed-linting), then you just need to ensure that the `tsconfig.json` you've configured for `parserOptions.project` has `emitDecoratorMetadata` turned on. Otherwise you can explicitly tell our tooling to analyze your code as if the compiler option was turned on [by setting `parserOptions.emitDecoratorMetadata` to `true`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/README.md#parseroptionsemitdecoratormetadata). + ## When Not To Use It - If you specifically want to use both import kinds for stylistic reasons, you can disable this rule.