From 84b4a8c5a67bc8da586cb00589fd56737a261885 Mon Sep 17 00:00:00 2001 From: Armano Date: Wed, 17 Nov 2021 19:08:06 +0100 Subject: [PATCH] docs(website): add remark plugin for tabs and apply it to rules (#4128) * docs(website): add remark plugin for tabs and apply it to rules * docs(website): correct markdown linting issues * docs(website): update tabs remark plugin * docs(website): update documentation pages * docs(website): correct heading in await-thenable * docs(website): refactor remark tabs to be excluded from toc * docs(website): move license to standalone file * docs(eslint-plugin): update remaining rules docs Co-authored-by: Brad Zacher --- .../rules/adjacent-overload-signatures.md | 6 +- .../eslint-plugin/docs/rules/array-type.md | 18 ++- .../docs/rules/await-thenable.md | 8 +- .../docs/rules/ban-ts-comment.md | 22 +++- .../docs/rules/ban-tslint-comment.md | 10 +- .../eslint-plugin/docs/rules/ban-types.md | 8 +- .../rules/class-literal-property-style.md | 64 ++++++---- .../rules/consistent-indexed-object-style.md | 20 ++- .../docs/rules/consistent-type-assertions.md | 28 +++- .../docs/rules/consistent-type-definitions.md | 20 ++- .../docs/rules/consistent-type-exports.md | 8 +- .../docs/rules/default-param-last.md | 6 +- .../rules/explicit-function-return-type.md | 46 +++++-- .../rules/explicit-module-boundary-types.md | 44 +++++-- .../docs/rules/member-delimiter-style.md | 8 +- .../docs/rules/method-signature-style.md | 20 ++- .../docs/rules/no-array-constructor.md | 6 +- .../docs/rules/no-base-to-string.md | 6 +- .../rules/no-confusing-non-null-assertion.md | 6 +- .../rules/no-confusing-void-expression.md | 6 +- .../docs/rules/no-dynamic-delete.md | 30 +++-- .../docs/rules/no-empty-function.md | 2 - .../docs/rules/no-empty-interface.md | 8 +- .../docs/rules/no-explicit-any.md | 6 +- .../docs/rules/no-extra-non-null-assertion.md | 8 +- .../docs/rules/no-extraneous-class.md | 10 +- .../docs/rules/no-floating-promises.md | 8 +- .../docs/rules/no-for-in-array.md | 8 +- .../docs/rules/no-implicit-any-catch.md | 8 +- .../docs/rules/no-implied-eval.md | 8 +- .../docs/rules/no-inferrable-types.md | 10 +- .../docs/rules/no-invalid-void-type.md | 14 +- .../rules/no-meaningless-void-operator.md | 10 +- .../docs/rules/no-misused-new.md | 8 +- .../docs/rules/no-misused-promises.md | 106 ++++++++++------ .../eslint-plugin/docs/rules/no-namespace.md | 36 ++++-- ...no-non-null-asserted-nullish-coalescing.md | 8 +- .../no-non-null-asserted-optional-chain.md | 8 +- .../docs/rules/no-non-null-assertion.md | 8 +- .../docs/rules/no-parameter-properties.md | 64 +++++++--- .../docs/rules/no-require-imports.md | 8 +- .../docs/rules/no-restricted-imports.md | 26 ++-- .../eslint-plugin/docs/rules/no-this-alias.md | 2 +- .../docs/rules/no-throw-literal.md | 8 +- .../no-unnecessary-boolean-literal-compare.md | 24 +++- .../docs/rules/no-unnecessary-condition.md | 10 +- .../docs/rules/no-unnecessary-qualifier.md | 8 +- .../rules/no-unnecessary-type-arguments.md | 8 +- .../rules/no-unnecessary-type-assertion.md | 10 +- .../rules/no-unnecessary-type-constraint.md | 8 +- .../docs/rules/no-unsafe-argument.md | 10 +- .../docs/rules/no-unsafe-assignment.md | 10 +- .../docs/rules/no-unsafe-call.md | 8 +- .../docs/rules/no-unsafe-member-access.md | 8 +- .../docs/rules/no-unsafe-return.md | 10 +- .../docs/rules/no-use-before-define.md | 8 +- .../docs/rules/no-var-requires.md | 8 +- .../non-nullable-type-assertion-style.md | 8 +- .../docs/rules/prefer-as-const.md | 10 +- .../docs/rules/prefer-enum-initializers.md | 8 +- .../eslint-plugin/docs/rules/prefer-for-of.md | 8 +- .../docs/rules/prefer-function-type.md | 8 +- .../docs/rules/prefer-includes.md | 8 +- .../docs/rules/prefer-literal-enum-member.md | 18 ++- .../docs/rules/prefer-optional-chain.md | 8 +- .../rules/prefer-readonly-parameter-types.md | 36 ++++-- .../docs/rules/prefer-readonly.md | 22 ++-- .../rules/prefer-reduce-type-parameter.md | 8 +- .../docs/rules/prefer-regexp-exec.md | 8 +- .../docs/rules/prefer-return-this-type.md | 10 +- .../rules/prefer-string-starts-ends-with.md | 8 +- .../docs/rules/prefer-ts-expect-error.md | 8 +- .../docs/rules/promise-function-async.md | 8 +- .../docs/rules/require-array-sort-compare.md | 16 ++- .../docs/rules/restrict-plus-operands.md | 28 ++-- .../rules/restrict-template-expressions.md | 24 ++-- .../eslint-plugin/docs/rules/return-await.md | 24 +++- .../sort-type-union-intersection-members.md | 8 +- .../docs/rules/strict-boolean-expressions.md | 8 +- .../docs/rules/switch-exhaustiveness-check.md | 12 +- .../docs/rules/type-annotation-spacing.md | 40 ++++-- packages/eslint-plugin/docs/rules/typedef.md | 64 +++++++--- .../docs/rules/unbound-method.md | 8 +- packages/website/docusaurus.config.js | 12 +- packages/website/src/remark/tabs.js | 120 ++++++++++++++++++ packages/website/src/remark/tabs.license.md | 23 ++++ 86 files changed, 1099 insertions(+), 374 deletions(-) create mode 100644 packages/website/src/remark/tabs.js create mode 100644 packages/website/src/remark/tabs.license.md diff --git a/packages/eslint-plugin/docs/rules/adjacent-overload-signatures.md b/packages/eslint-plugin/docs/rules/adjacent-overload-signatures.md index 339425c8d42..cdd49a0b032 100644 --- a/packages/eslint-plugin/docs/rules/adjacent-overload-signatures.md +++ b/packages/eslint-plugin/docs/rules/adjacent-overload-signatures.md @@ -6,7 +6,9 @@ Grouping overloaded members together can improve readability of the code. This rule aims to standardize the way overloaded members are organized. -The following patterns are considered warnings: + + +### ❌ Incorrect ```ts declare namespace Foo { @@ -43,7 +45,7 @@ export function bar(): void; export function foo(sn: string | number): void; ``` -The following patterns are not warnings: +### ✅ Correct ```ts declare namespace Foo { diff --git a/packages/eslint-plugin/docs/rules/array-type.md b/packages/eslint-plugin/docs/rules/array-type.md index 66f0bcb750b..33f6cfe34fb 100644 --- a/packages/eslint-plugin/docs/rules/array-type.md +++ b/packages/eslint-plugin/docs/rules/array-type.md @@ -33,14 +33,16 @@ The default config will enforce that all mutable and readonly arrays use the `'a Always use `T[]` or `readonly T[]` for all array types. -Incorrect code for `"array"`: + + +#### ❌ Incorrect ```ts const x: Array = ['a', 'b']; const y: ReadonlyArray = ['a', 'b']; ``` -Correct code for `"array"`: +#### ✅ Correct ```ts const x: string[] = ['a', 'b']; @@ -51,14 +53,16 @@ const y: readonly string[] = ['a', 'b']; Always use `Array` or `ReadonlyArray` for all array types. -Incorrect code for `"generic"`: + + +#### ❌ Incorrect ```ts const x: string[] = ['a', 'b']; const y: readonly string[] = ['a', 'b']; ``` -Correct code for `"generic"`: +#### ✅ Correct ```ts const x: Array = ['a', 'b']; @@ -70,7 +74,9 @@ const y: ReadonlyArray = ['a', 'b']; Use `T[]` or `readonly T[]` for simple types (i.e. types which are just primitive names or type references). Use `Array` or `ReadonlyArray` for all other types (union types, intersection types, object types, function types, etc). -Incorrect code for `"array-simple"`: + + +#### ❌ Incorrect ```ts const a: (string | number)[] = ['a', 'b']; @@ -81,7 +87,7 @@ const e: Array = ['a', 'b']; const f: ReadonlyArray = ['a', 'b']; ``` -Correct code for `"array-simple"`: +#### ✅ Correct ```ts const a: Array = ['a', 'b']; diff --git a/packages/eslint-plugin/docs/rules/await-thenable.md b/packages/eslint-plugin/docs/rules/await-thenable.md index c4046cbf988..835285d2658 100644 --- a/packages/eslint-plugin/docs/rules/await-thenable.md +++ b/packages/eslint-plugin/docs/rules/await-thenable.md @@ -5,7 +5,11 @@ While it is valid JavaScript to await a non-`Promise`-like value (it will resolv ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts await 'value'; @@ -14,7 +18,7 @@ const createValue = () => 'value'; await createValue(); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts await Promise.resolve('value'); diff --git a/packages/eslint-plugin/docs/rules/ban-ts-comment.md b/packages/eslint-plugin/docs/rules/ban-ts-comment.md index f9727887603..51051d6a305 100644 --- a/packages/eslint-plugin/docs/rules/ban-ts-comment.md +++ b/packages/eslint-plugin/docs/rules/ban-ts-comment.md @@ -41,7 +41,9 @@ const defaultOptions: Options = { A value of `true` for a particular directive means that this rule will report if it finds any usage of said directive. -For example, with the defaults above the following patterns are considered warnings for single line or comment block lines: + + +#### ❌ Incorrect ```ts if (false) { @@ -56,7 +58,7 @@ if (false) { } ``` -The following patterns are not warnings: +#### ✅ Correct ```ts if (false) { @@ -69,7 +71,11 @@ if (false) { A value of `'allow-with-description'` for a particular directive means that this rule will report if it finds a directive that does not have a description following the directive (on the same line). -For example, with `{ 'ts-expect-error': 'allow-with-description' }` the following patterns are considered a warning: +For example, with `{ 'ts-expect-error': 'allow-with-description' }`: + + + +#### ❌ Incorrect ```ts if (false) { @@ -82,7 +88,7 @@ if (false) { } ``` -The following patterns are not a warning: +#### ✅ Correct ```ts if (false) { @@ -101,7 +107,11 @@ if (false) { Use `minimumDescriptionLength` to set a minimum length for descriptions when using the `allow-with-description` option for a directive. -For example, with `{ 'ts-expect-error': 'allow-with-description', minimumDescriptionLength: 10 }` the following pattern is considered a warning: +For example, with `{ 'ts-expect-error': 'allow-with-description', minimumDescriptionLength: 10 }` the following pattern is: + + + +#### ❌ Incorrect ```ts if (false) { @@ -110,7 +120,7 @@ if (false) { } ``` -The following pattern is not a warning: +#### ✅ Correct ```ts if (false) { diff --git a/packages/eslint-plugin/docs/rules/ban-tslint-comment.md b/packages/eslint-plugin/docs/rules/ban-tslint-comment.md index 48e49c1ddcb..121fcaf5ea9 100644 --- a/packages/eslint-plugin/docs/rules/ban-tslint-comment.md +++ b/packages/eslint-plugin/docs/rules/ban-tslint-comment.md @@ -4,10 +4,12 @@ Useful when migrating from TSLint to ESLint. Once TSLint has been removed, this ## Rule Details -Examples of **incorrect** code for this rule: - All TSLint [rule flags](https://palantir.github.io/tslint/usage/rule-flags/) + + +### ❌ Incorrect + ```js /* tslint:disable */ /* tslint:enable */ @@ -18,10 +20,12 @@ someCode(); // tslint:disable-line // tslint:disable-next-line:rule1 rule2 rule3... ``` -Examples of **correct** code for this rule: +### ✅ Correct ```js // This is a comment that just happens to mention tslint +/* This is a multiline comment that just happens to mention tslint */ +someCode(); // This is a comment that just happens to mention tslint ``` ## When Not To Use It diff --git a/packages/eslint-plugin/docs/rules/ban-types.md b/packages/eslint-plugin/docs/rules/ban-types.md index 0fc1c3af94b..620ef8ece0a 100644 --- a/packages/eslint-plugin/docs/rules/ban-types.md +++ b/packages/eslint-plugin/docs/rules/ban-types.md @@ -131,7 +131,11 @@ const defaultTypes = { ### Examples -Examples of **incorrect** code with the default options: +Examples of code with the default options: + + + +#### ❌ Incorrect ```ts // use lower-case primitives for consistency @@ -151,7 +155,7 @@ const curly1: {} = 1; const curly2: {} = { a: 'string' }; ``` -Examples of **correct** code with the default options: +#### ✅ Correct ```ts // use lower-case primitives for consistency diff --git a/packages/eslint-plugin/docs/rules/class-literal-property-style.md b/packages/eslint-plugin/docs/rules/class-literal-property-style.md index 220d858f03c..fc583724228 100644 --- a/packages/eslint-plugin/docs/rules/class-literal-property-style.md +++ b/packages/eslint-plugin/docs/rules/class-literal-property-style.md @@ -15,37 +15,41 @@ This is because these types can be mutated and carry with them more complex impl This style checks for any getter methods that return literal values, and requires them to be defined using fields with the `readonly` modifier instead. -Examples of **correct** code with the `fields` style: +Examples of code with the `fields` style: + + + +#### ❌ Incorrect ```ts /* eslint @typescript-eslint/class-literal-property-style: ["error", "fields"] */ class Mx { - public readonly myField1 = 1; - - // not a literal - public readonly myField2 = [1, 2, 3]; - - private readonly ['myField3'] = 'hello world'; + public static get myField1() { + return 1; + } - public get myField4() { - return `hello from ${window.location.href}`; + private get ['myField2']() { + return 'hello world'; } } ``` -Examples of **incorrect** code with the `fields` style: +#### ✅ Correct ```ts /* eslint @typescript-eslint/class-literal-property-style: ["error", "fields"] */ class Mx { - public static get myField1() { - return 1; - } + public readonly myField1 = 1; - private get ['myField2']() { - return 'hello world'; + // not a literal + public readonly myField2 = [1, 2, 3]; + + private readonly ['myField3'] = 'hello world'; + + public get myField4() { + return `hello from ${window.location.href}`; } } ``` @@ -56,7 +60,23 @@ This style checks for any `readonly` fields that are assigned literal values, an This style pairs well with the [`@typescript-eslint/prefer-readonly`](prefer-readonly.md) rule, as it will identify fields that can be `readonly`, and thus should be made into getters. -Examples of **correct** code with the `getters` style: +Examples of code with the `getters` style: + + + +#### ❌ Incorrect + +```ts +/* eslint @typescript-eslint/class-literal-property-style: ["error", "getters"] */ + +class Mx { + readonly myField1 = 1; + readonly myField2 = `hello world`; + private readonly myField3 = 'hello world'; +} +``` + +#### ✅ Correct ```ts /* eslint @typescript-eslint/class-literal-property-style: ["error", "getters"] */ @@ -78,18 +98,6 @@ class Mx { } ``` -Examples of **incorrect** code with the `getters` style: - -```ts -/* eslint @typescript-eslint/class-literal-property-style: ["error", "getters"] */ - -class Mx { - readonly myField1 = 1; - readonly myField2 = `hello world`; - private readonly myField3 = 'hello world'; -} -``` - ## When Not To Use It When you have no strong preference, or do not wish to enforce a particular style diff --git a/packages/eslint-plugin/docs/rules/consistent-indexed-object-style.md b/packages/eslint-plugin/docs/rules/consistent-indexed-object-style.md index 1aa12cb4484..63fd4386e8a 100644 --- a/packages/eslint-plugin/docs/rules/consistent-indexed-object-style.md +++ b/packages/eslint-plugin/docs/rules/consistent-indexed-object-style.md @@ -33,7 +33,13 @@ For example: This rule enforces a consistent way to define records. -Examples of **incorrect** code with `record` option. +### `record` + +Examples of code with `record` option. + + + +#### ❌ Incorrect ```ts interface Foo { @@ -45,19 +51,25 @@ type Foo = { }; ``` -Examples of **correct** code with `record` option. +#### ✅ Correct ```ts type Foo = Record; ``` -Examples of **incorrect** code with `index-signature` option. +### `index-signature` + +Examples of code with `index-signature` option. + + + +#### ❌ Incorrect ```ts type Foo = Record; ``` -Examples of **correct** code with `index-signature` option. +#### ✅ Correct ```ts interface Foo { diff --git a/packages/eslint-plugin/docs/rules/consistent-type-assertions.md b/packages/eslint-plugin/docs/rules/consistent-type-assertions.md index 56a3cbddde2..f4d46ac79fb 100644 --- a/packages/eslint-plugin/docs/rules/consistent-type-assertions.md +++ b/packages/eslint-plugin/docs/rules/consistent-type-assertions.md @@ -50,7 +50,11 @@ The const assertion `const x = { foo: 1 } as const`, introduced in TypeScript 3. Assertions to `any` are also ignored by this option. -Examples of **incorrect** code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }` (and for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'allow-as-parameter' }`) +Examples of code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }` + + + +#### ❌ Incorrect ```ts const x = { ... } as T; @@ -60,7 +64,7 @@ function foo() { } ``` -Examples of **correct** code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }`. +#### ✅ Correct ```ts const x: T = { ... }; @@ -72,7 +76,23 @@ function foo(): T { } ``` -Examples of **correct** code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'allow-as-parameter' }`. + + +Examples of code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'allow-as-parameter' }` + + + +#### ❌ Incorrect + +```ts +const x = { ... } as T; + +function foo() { + return { ... } as T; +} +``` + +#### ✅ Correct ```tsx const x: T = { ... }; @@ -84,6 +104,8 @@ function foo() { throw { bar: 5 } as Foo } const foo = ; ``` + + ## When Not To Use It If you do not want to enforce consistent type assertions. diff --git a/packages/eslint-plugin/docs/rules/consistent-type-definitions.md b/packages/eslint-plugin/docs/rules/consistent-type-definitions.md index 6f91d480e52..4efe6594e17 100644 --- a/packages/eslint-plugin/docs/rules/consistent-type-definitions.md +++ b/packages/eslint-plugin/docs/rules/consistent-type-definitions.md @@ -32,15 +32,19 @@ For example: } ``` -## Rule Details +### `interface` -Examples of **incorrect** code with `interface` option. +Examples of code with `interface` option. + + + +#### ❌ Incorrect ```ts type T = { x: number }; ``` -Examples of **correct** code with `interface` option. +#### ✅ Correct ```ts type T = string; @@ -51,7 +55,13 @@ interface T { } ``` -Examples of **incorrect** code with `type` option. +### `type` + +Examples of code with `type` option. + + + +#### ❌ Incorrect ```ts interface T { @@ -59,7 +69,7 @@ interface T { } ``` -Examples of **correct** code with `type` option. +#### ✅ Correct ```ts type T = { x: number }; diff --git a/packages/eslint-plugin/docs/rules/consistent-type-exports.md b/packages/eslint-plugin/docs/rules/consistent-type-exports.md index cb3b01f51df..71303d3659e 100644 --- a/packages/eslint-plugin/docs/rules/consistent-type-exports.md +++ b/packages/eslint-plugin/docs/rules/consistent-type-exports.md @@ -9,14 +9,18 @@ transpilers to drop exports without knowing the types of the dependencies. This rule aims to standardize the use of type exports style across a codebase. -Given a class `Button`, and an interface `ButtonProps`, examples of **correct** code: +Given a class `Button`, and an interface `ButtonProps`, examples of code: + + + +### ❌ Incorrect ```ts export { Button } from 'some-library'; export type { ButtonProps } from 'some-library'; ``` -Examples of **incorrect** code: +### ✅ Correct ```ts export { Button, ButtonProps } from 'some-library'; diff --git a/packages/eslint-plugin/docs/rules/default-param-last.md b/packages/eslint-plugin/docs/rules/default-param-last.md index 0e671562efa..b2d241fdd94 100644 --- a/packages/eslint-plugin/docs/rules/default-param-last.md +++ b/packages/eslint-plugin/docs/rules/default-param-last.md @@ -5,7 +5,9 @@ This rule extends the base [`eslint/default-param-last`](https://eslint.org/docs/rules/default-param-last) rule. It adds support for optional parameters. -Examples of **incorrect** code for this rule: + + +### ❌ Incorrect ```ts /* eslint @typescript-eslint/default-param-last: ["error"] */ @@ -21,7 +23,7 @@ class Foo { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /* eslint @typescript-eslint/default-param-last: ["error"] */ diff --git a/packages/eslint-plugin/docs/rules/explicit-function-return-type.md b/packages/eslint-plugin/docs/rules/explicit-function-return-type.md index 27e731d3d84..4c199878bb1 100644 --- a/packages/eslint-plugin/docs/rules/explicit-function-return-type.md +++ b/packages/eslint-plugin/docs/rules/explicit-function-return-type.md @@ -9,7 +9,9 @@ shouldn't. This rule aims to ensure that the values returned from functions are of the expected type. -The following patterns are considered warnings: + + +### ❌ Incorrect ```ts // Should indicate that no value is returned (void) @@ -33,7 +35,7 @@ class Test { } ``` -The following patterns are not warnings: +### ✅ Correct ```ts // No return value should be expected (void) @@ -108,7 +110,11 @@ If you are working on a codebase within which you lint non-TypeScript code (i.e. ### `allowExpressions` -Examples of **incorrect** code for this rule with `{ allowExpressions: true }`: +Examples of code for this rule with `{ allowExpressions: true }`: + + + +#### ❌ Incorrect ```ts function test() {} @@ -118,7 +124,7 @@ const fn = () => {}; export default () => {}; ``` -Examples of **correct** code for this rule with `{ allowExpressions: true }`: +#### ✅ Correct ```ts node.addEventListener('click', () => {}); @@ -130,7 +136,11 @@ const foo = arr.map(i => i * i); ### `allowTypedFunctionExpressions` -Examples of **incorrect** code for this rule with `{ allowTypedFunctionExpressions: true }`: +Examples of code for this rule with `{ allowTypedFunctionExpressions: true }`: + + + +#### ❌ Incorrect ```ts let arrowFn = () => 'test'; @@ -144,7 +154,7 @@ let objectProp = { }; ``` -Examples of additional **correct** code for this rule with `{ allowTypedFunctionExpressions: true }`: +#### ✅ Correct ```ts type FuncType = () => string; @@ -184,7 +194,11 @@ functionWithObjectArg({ ### `allowHigherOrderFunctions` -Examples of **incorrect** code for this rule with `{ allowHigherOrderFunctions: true }`: +Examples of code for this rule with `{ allowHigherOrderFunctions: true }`: + + + +#### ❌ Incorrect ```ts var arrowFn = () => () => {}; @@ -194,7 +208,7 @@ function fn() { } ``` -Examples of **correct** code for this rule with `{ allowHigherOrderFunctions: true }`: +#### ✅ Correct ```ts var arrowFn = () => (): void => {}; @@ -206,14 +220,18 @@ function fn() { ### `allowDirectConstAssertionInArrowFunctions` -Examples of **incorrect** code for this rule with `{ allowDirectConstAssertionInArrowFunctions: true }`: +Examples of code for this rule with `{ allowDirectConstAssertionInArrowFunctions: true }`: + + + +#### ❌ Incorrect ```ts const func = (value: number) => ({ type: 'X', value } as any); const func = (value: number) => ({ type: 'X', value } as Action); ``` -Examples of **correct** code for this rule with `{ allowDirectConstAssertionInArrowFunctions: true }`: +#### ✅ Correct ```ts const func = (value: number) => ({ foo: 'bar', value } as const); @@ -222,7 +240,11 @@ const func = () => x as const; ### `allowConciseArrowFunctionExpressionsStartingWithVoid` -Examples of **incorrect** code for this rule with `{ allowConciseArrowFunctionExpressionsStartingWithVoid: true }`: +Examples of code for this rule with `{ allowConciseArrowFunctionExpressionsStartingWithVoid: true }`: + + + +#### ❌ Incorrect ```ts var join = (a: string, b: string) => `${a}${b}`; @@ -232,7 +254,7 @@ const log = (message: string) => { }; ``` -Examples of **correct** code for this rule with `{ allowConciseArrowFunctionExpressionsStartingWithVoid: true }`: +#### ✅ Correct ```ts var log = (message: string) => void console.log(message); diff --git a/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md b/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md index fe3b92b7b3d..f857b813ba9 100644 --- a/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md +++ b/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md @@ -6,7 +6,9 @@ Explicit types for function return values and arguments makes it clear to any ca This rule aims to ensure that the values returned from a module are of the expected type. -The following patterns are considered warnings: + + +### ❌ Incorrect ```ts // Should indicate that no value is returned (void) @@ -34,7 +36,7 @@ export class Test { } ``` -The following patterns are not warnings: +### ✅ Correct ```ts // Function is not exported @@ -128,13 +130,17 @@ If you are working on a codebase within which you lint non-TypeScript code (i.e. ### `allowArgumentsExplicitlyTypedAsAny` -Examples of **incorrect** code for this rule with `{ allowArgumentsExplicitlyTypedAsAny: false }`: +Examples of code for this rule with `{ allowArgumentsExplicitlyTypedAsAny: false }`: + + + +#### ❌ Incorrect ```ts export const func = (value: any): number => value + 1; ``` -Examples of **correct** code for this rule with `{ allowArgumentsExplicitlyTypedAsAny: true }`: +#### ✅ Correct ```ts export const func = (value: number): number => value + 1; @@ -142,7 +148,11 @@ export const func = (value: number): number => value + 1; ### `allowDirectConstAssertionInArrowFunctions` -Examples of **incorrect** code for this rule with `{ allowDirectConstAssertionInArrowFunctions: false }`: +Examples of code for this rule with `{ allowDirectConstAssertionInArrowFunctions: false }`: + + + +#### ❌ Incorrect ```ts export const func = (value: number) => ({ type: 'X', value }); @@ -153,7 +163,7 @@ export const foo = () => export const bar = () => 1; ``` -Examples of **correct** code for this rule with `{ allowDirectConstAssertionInArrowFunctions: true }`: +#### ✅ Correct ```ts export const func = (value: number) => ({ type: 'X', value } as const); @@ -181,21 +191,25 @@ You may pass function/method names you would like this rule to ignore, like so: ### `allowHigherOrderFunctions` -Examples of **incorrect** code for this rule with `{ allowHigherOrderFunctions: false }`: +Examples of code for this rule with `{ allowHigherOrderFunctions: false }`: + + + +#### ❌ Incorrect ```ts -export const arrowFn = () => (): void => {}; +export const arrowFn = () => () => {}; export function fn() { - return function (): void {}; + return function () {}; } export function foo(outer: string) { - return function (inner: string): void {}; + return function (inner: string) {}; } ``` -Examples of **correct** code for this rule with `{ allowHigherOrderFunctions: true }`: +#### ✅ Correct ```ts export const arrowFn = () => (): void => {}; @@ -211,7 +225,11 @@ export function foo(outer: string) { ### `allowTypedFunctionExpressions` -Examples of **incorrect** code for this rule with `{ allowTypedFunctionExpressions: false }`: +Examples of code for this rule with `{ allowTypedFunctionExpressions: false }`: + + + +#### ❌ Incorrect ```ts export let arrowFn = () => 'test'; @@ -227,7 +245,7 @@ export let objectProp = { export const foo = bar => {}; ``` -Examples of additional **correct** code for this rule with `{ allowTypedFunctionExpressions: true }`: +#### ✅ Correct ```ts type FuncType = () => string; diff --git a/packages/eslint-plugin/docs/rules/member-delimiter-style.md b/packages/eslint-plugin/docs/rules/member-delimiter-style.md index 966a1a7fbda..4a979cd9fbe 100644 --- a/packages/eslint-plugin/docs/rules/member-delimiter-style.md +++ b/packages/eslint-plugin/docs/rules/member-delimiter-style.md @@ -149,7 +149,11 @@ For example, to require commas for `type`s, and semicolons for multiline `interf ## Examples -Examples of **incorrect** code for this rule with the default config: +Examples of code for this rule with the default config: + + + +### ❌ Incorrect ```ts @@ -178,7 +182,7 @@ type FooBar = { name: string, greet(): string } type FooBar = { name: string; greet(): string; } ``` -Examples of **correct** code for this rule with the default config: +### ✅ Correct ```ts diff --git a/packages/eslint-plugin/docs/rules/method-signature-style.md b/packages/eslint-plugin/docs/rules/method-signature-style.md index acfc4317db9..41215068355 100644 --- a/packages/eslint-plugin/docs/rules/method-signature-style.md +++ b/packages/eslint-plugin/docs/rules/method-signature-style.md @@ -32,9 +32,13 @@ This rule accepts one string option: The default is `"property"`. -## Rule Details +### `property` -Examples of **incorrect** code with `property` option. +Examples of code with `property` option. + + + +#### ❌ Incorrect ```ts interface T1 { @@ -50,7 +54,7 @@ interface T3 { } ``` -Examples of **correct** code with `property` option. +#### ✅ Correct ```ts interface T1 { @@ -67,7 +71,13 @@ interface T3 { } ``` -Examples of **incorrect** code with `method` option. +### `method` + +Examples of code with `method` option. + + + +#### ❌ Incorrect ```ts interface T1 { @@ -78,7 +88,7 @@ type T2 = { }; ``` -Examples of **correct** code with `method` option. +#### ✅ Correct ```ts interface T1 { diff --git a/packages/eslint-plugin/docs/rules/no-array-constructor.md b/packages/eslint-plugin/docs/rules/no-array-constructor.md index 86ff2cc4557..a707662a6f9 100644 --- a/packages/eslint-plugin/docs/rules/no-array-constructor.md +++ b/packages/eslint-plugin/docs/rules/no-array-constructor.md @@ -5,7 +5,9 @@ This rule extends the base [`eslint/no-array-constructor`](https://eslint.org/docs/rules/no-array-constructor) rule. It adds support for the generically typed `Array` constructor (`new Array()`). -Examples of **incorrect** code for this rule: + + +### ❌ Incorrect ```ts /*eslint no-array-constructor: "error"*/ @@ -14,7 +16,7 @@ Array(0, 1, 2); new Array(0, 1, 2); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /*eslint no-array-constructor: "error"*/ diff --git a/packages/eslint-plugin/docs/rules/no-base-to-string.md b/packages/eslint-plugin/docs/rules/no-base-to-string.md index 3daf5624792..5dd59bb2bb5 100644 --- a/packages/eslint-plugin/docs/rules/no-base-to-string.md +++ b/packages/eslint-plugin/docs/rules/no-base-to-string.md @@ -13,7 +13,9 @@ This rule has some overlap with [`restrict-plus-operands`](./restrict-plus-opera This rule prevents accidentally defaulting to the base Object `.toString()` method. -Examples of **incorrect** code for this rule: + + +### ❌ Incorrect ```ts // Passing an object or class instance to string concatenation: @@ -28,7 +30,7 @@ value + ''; ({}.toString()); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts // These types all have useful .toString()s diff --git a/packages/eslint-plugin/docs/rules/no-confusing-non-null-assertion.md b/packages/eslint-plugin/docs/rules/no-confusing-non-null-assertion.md index cac0acbc243..78655b69db8 100644 --- a/packages/eslint-plugin/docs/rules/no-confusing-non-null-assertion.md +++ b/packages/eslint-plugin/docs/rules/no-confusing-non-null-assertion.md @@ -10,7 +10,9 @@ a !== b; // not equals test(`!==`) a! === b; // a non-null assertions(`!`) and an triple equals test(`===`) ``` -Examples of **incorrect** code for this rule: + + +### ❌ Incorrect ```ts interface Foo { @@ -23,7 +25,7 @@ const isEqualsBar = foo.bar! == 'hello'; const isEqualsNum = 1 + foo.num! == 2; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts diff --git a/packages/eslint-plugin/docs/rules/no-confusing-void-expression.md b/packages/eslint-plugin/docs/rules/no-confusing-void-expression.md index 3ea101e18b4..b49ca52ebec 100644 --- a/packages/eslint-plugin/docs/rules/no-confusing-void-expression.md +++ b/packages/eslint-plugin/docs/rules/no-confusing-void-expression.md @@ -9,7 +9,9 @@ This rule provides automatic fixes for most common cases. ## Examples -Examples of **incorrect** code for this rule: + + +### ❌ Incorrect ```ts // somebody forgot that `alert` doesn't return anything @@ -29,7 +31,7 @@ function doSomething() { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts // just a regular void function in a statement position diff --git a/packages/eslint-plugin/docs/rules/no-dynamic-delete.md b/packages/eslint-plugin/docs/rules/no-dynamic-delete.md index 4d12eef8ffe..1ed24aa862c 100644 --- a/packages/eslint-plugin/docs/rules/no-dynamic-delete.md +++ b/packages/eslint-plugin/docs/rules/no-dynamic-delete.md @@ -8,7 +8,22 @@ Using the `delete` operator on keys that aren't runtime constants could be a sig Using `Object`s with added and removed keys can cause occasional edge case bugs, such as if a key is named `"hasOwnProperty"`. Consider using a `Map` or `Set` if you’re storing collections of objects. -Examples of **correct** code with this rule: + + +### ❌ Incorrect + +```ts +// Can be replaced with the constant equivalents, such as container.aaa +delete container['aaa']; +delete container['Infinity']; + +// Dynamic, difficult-to-reason-about lookups +const name = 'name'; +delete container[name]; +delete container[name.toUpperCase()]; +``` + +### ✅ Correct ```ts const container: { [i: string]: number } = { @@ -23,19 +38,6 @@ delete container[7]; delete container['-Infinity']; ``` -Examples of **incorrect** code with this rule: - -```ts -// Can be replaced with the constant equivalents, such as container.aaa -delete container['aaa']; -delete container['Infinity']; - -// Dynamic, difficult-to-reason-about lookups -const name = 'name'; -delete container[name]; -delete container[name.toUpperCase()]; -``` - ## When Not To Use It When you know your keys are safe to delete, this rule can be unnecessary. diff --git a/packages/eslint-plugin/docs/rules/no-empty-function.md b/packages/eslint-plugin/docs/rules/no-empty-function.md index c9cfa8eb792..a313e1eb826 100644 --- a/packages/eslint-plugin/docs/rules/no-empty-function.md +++ b/packages/eslint-plugin/docs/rules/no-empty-function.md @@ -85,8 +85,6 @@ class Foo { } ``` ---- - Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/master/docs/rules/no-empty-function.md) diff --git a/packages/eslint-plugin/docs/rules/no-empty-interface.md b/packages/eslint-plugin/docs/rules/no-empty-interface.md index 5eca9c8af10..178a17577af 100644 --- a/packages/eslint-plugin/docs/rules/no-empty-interface.md +++ b/packages/eslint-plugin/docs/rules/no-empty-interface.md @@ -7,7 +7,9 @@ the interface is equivalent to an empty object (`{}`). In both cases it can be o This rule aims to ensure that only meaningful interfaces are declared in the code. -The following patterns are considered warnings: + + +### ❌ Incorrect ```ts // an empty interface @@ -20,7 +22,7 @@ interface Bar extends Foo {} interface Baz {} ``` -The following patterns are not warnings: +### ✅ Correct ```ts // an interface with any number of members @@ -38,6 +40,8 @@ interface Bar { interface Baz extends Foo, Bar {} ``` + + ### Options This rule accepts a single object option with the following default configuration: diff --git a/packages/eslint-plugin/docs/rules/no-explicit-any.md b/packages/eslint-plugin/docs/rules/no-explicit-any.md index 85256e33c71..cb365f7b65f 100644 --- a/packages/eslint-plugin/docs/rules/no-explicit-any.md +++ b/packages/eslint-plugin/docs/rules/no-explicit-any.md @@ -11,7 +11,9 @@ TypeScript has a compiler flag for `--noImplicitAny` that will prevent an `any` type from being implied by the compiler, but doesn't prevent `any` from being explicitly used. -The following patterns are considered warnings: + + +### ❌ Incorrect ```ts const age: any = 'seventeen'; @@ -49,7 +51,7 @@ function greet(param: Array): string {} function greet(param: Array): Array {} ``` -The following patterns are not warnings: +### ✅ Correct ```ts const age: number = 17; diff --git a/packages/eslint-plugin/docs/rules/no-extra-non-null-assertion.md b/packages/eslint-plugin/docs/rules/no-extra-non-null-assertion.md index 8eb27f805c4..af89da22f1d 100644 --- a/packages/eslint-plugin/docs/rules/no-extra-non-null-assertion.md +++ b/packages/eslint-plugin/docs/rules/no-extra-non-null-assertion.md @@ -2,7 +2,11 @@ ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const foo: { bar: number } | null = null; @@ -21,7 +25,7 @@ function foo(bar?: { n: number }) { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts const foo: { bar: number } | null = null; diff --git a/packages/eslint-plugin/docs/rules/no-extraneous-class.md b/packages/eslint-plugin/docs/rules/no-extraneous-class.md index 5a57c71ec4f..a96f4ff40e0 100644 --- a/packages/eslint-plugin/docs/rules/no-extraneous-class.md +++ b/packages/eslint-plugin/docs/rules/no-extraneous-class.md @@ -9,7 +9,11 @@ From TSLint’s docs: > Users who come from a Java-style OO language may wrap their utility functions in an extra class, > instead of putting them at the top level. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts class EmptyClass {} @@ -29,7 +33,7 @@ class StaticOnly { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts class EmptyClass extends SuperClass {} @@ -46,7 +50,7 @@ const StaticOnly = { }; ``` -### Options +## Options This rule accepts a single object option. diff --git a/packages/eslint-plugin/docs/rules/no-floating-promises.md b/packages/eslint-plugin/docs/rules/no-floating-promises.md index 1e7d0bf3299..f0a9a83c08f 100644 --- a/packages/eslint-plugin/docs/rules/no-floating-promises.md +++ b/packages/eslint-plugin/docs/rules/no-floating-promises.md @@ -8,7 +8,11 @@ either calling `.then()` with two arguments or `.catch()` with one argument. ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const promise = new Promise((resolve, reject) => resolve('value')); @@ -24,7 +28,7 @@ Promise.reject('value').catch(); Promise.reject('value').finally(); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts const promise = new Promise((resolve, reject) => resolve('value')); diff --git a/packages/eslint-plugin/docs/rules/no-for-in-array.md b/packages/eslint-plugin/docs/rules/no-for-in-array.md index 61ab8e0c118..d060781310c 100644 --- a/packages/eslint-plugin/docs/rules/no-for-in-array.md +++ b/packages/eslint-plugin/docs/rules/no-for-in-array.md @@ -19,7 +19,11 @@ for (const [index, value] of array.entries()) { ... } for (let i = 0; i < array.length; i++) { ... } ``` -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```js for (const x in [3, 4, 5]) { @@ -27,7 +31,7 @@ for (const x in [3, 4, 5]) { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```js for (const x in { a: 3, b: 4, c: 5 }) { diff --git a/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md b/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md index 81ac098690e..9ba72d0c92c 100644 --- a/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md +++ b/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md @@ -10,7 +10,11 @@ The `noImplicitAny` flag in TypeScript does not cover this for backwards compati This rule requires an explicit type to be declared on a catch clause variable. -The following pattern is considered a warning: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts try { @@ -20,7 +24,7 @@ try { } ``` -The following pattern is **_not_** considered a warning: +### ✅ Correct diff --git a/packages/eslint-plugin/docs/rules/no-implied-eval.md b/packages/eslint-plugin/docs/rules/no-implied-eval.md index d54d53e5aaf..347e14bda57 100644 --- a/packages/eslint-plugin/docs/rules/no-implied-eval.md +++ b/packages/eslint-plugin/docs/rules/no-implied-eval.md @@ -23,7 +23,11 @@ The best practice is to avoid using `new Function()` or `execScript()` and alway This rule aims to eliminate implied `eval()` through the use of `new Function()`, `setTimeout()`, `setInterval()`, `setImmediate()` or `execScript()`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts /* eslint @typescript-eslint/no-implied-eval: "error" */ @@ -51,7 +55,7 @@ setTimeout(fn(), 100); const fn = new Function('a', 'b', 'return a + b'); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /* eslint @typescript-eslint/no-implied-eval: "error" */ diff --git a/packages/eslint-plugin/docs/rules/no-inferrable-types.md b/packages/eslint-plugin/docs/rules/no-inferrable-types.md index f94c58671f8..a79d5af8915 100644 --- a/packages/eslint-plugin/docs/rules/no-inferrable-types.md +++ b/packages/eslint-plugin/docs/rules/no-inferrable-types.md @@ -29,7 +29,11 @@ The default options are: } ``` -With these options, the following patterns are valid: +With these options, the following patterns are: + + + +#### ❌ Correct ```ts const a = 10n; @@ -72,7 +76,7 @@ function fn(a = 5, b = true) {} function fn(a: number, b: boolean, c: string) {} ``` -The following are invalid: +#### ❌ Incorrect ```ts const a: bigint = 10n; @@ -113,6 +117,8 @@ class Foo { function fn(a: number = 5, b: boolean = true) {} ``` + + ### `ignoreParameters` When set to true, the following pattern is considered valid: diff --git a/packages/eslint-plugin/docs/rules/no-invalid-void-type.md b/packages/eslint-plugin/docs/rules/no-invalid-void-type.md index 7ba22334893..d9a97de401d 100644 --- a/packages/eslint-plugin/docs/rules/no-invalid-void-type.md +++ b/packages/eslint-plugin/docs/rules/no-invalid-void-type.md @@ -14,7 +14,11 @@ If you need this - use the `undefined` type instead. This rule aims to ensure that the `void` type is only used in valid places. -The following patterns are considered warnings: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts type PossibleValues = string | number | void; @@ -35,7 +39,7 @@ class MyClass { } ``` -The following patterns are not considered warnings: +### ✅ Correct ```ts type NoOp = () => void; @@ -49,7 +53,7 @@ async function promiseMeSomething(): Promise {} type stillVoid = void | never; ``` -### Options +## Options ```ts interface Options { @@ -63,7 +67,7 @@ const defaultOptions: Options = { }; ``` -#### `allowInGenericTypeArguments` +### `allowInGenericTypeArguments` This option lets you control if `void` can be used as a valid value for generic type parameters. @@ -99,7 +103,7 @@ type AllowedVoid = Ex.Mx.Tx; type AllowedVoidUnion = void | Ex.Mx.Tx; ``` -#### `allowAsThisParameter` +### `allowAsThisParameter` This option allows specifying a `this` parameter of a function to be `void` when set to `true`. This pattern can be useful to explicitly label function types that do not use a `this` argument. [See the TypeScript docs for more information](https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters-in-callbacks). diff --git a/packages/eslint-plugin/docs/rules/no-meaningless-void-operator.md b/packages/eslint-plugin/docs/rules/no-meaningless-void-operator.md index c9479679f41..f1ddff9e219 100644 --- a/packages/eslint-plugin/docs/rules/no-meaningless-void-operator.md +++ b/packages/eslint-plugin/docs/rules/no-meaningless-void-operator.md @@ -8,7 +8,11 @@ The `void` operator is a useful tool to convey the programmer's intent to discar This rule helps an author catch API changes where previously a value was being discarded at a call site, but the callee changed so it no longer returns a value. When combined with [no-unused-expressions](https://eslint.org/docs/rules/no-unused-expressions), it also helps _readers_ of the code by ensuring consistency: a statement that looks like `void foo();` is **always** discarding a return value, and a statement that looks like `foo();` is **never** discarding a return value. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts void (() => {})(); @@ -17,7 +21,7 @@ function foo() {} void foo(); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts (() => {})(); @@ -32,7 +36,7 @@ function bar(x: number) { void bar(); // discarding a number ``` -### Options +## Options This rule accepts a single object option with the following default configuration: diff --git a/packages/eslint-plugin/docs/rules/no-misused-new.md b/packages/eslint-plugin/docs/rules/no-misused-new.md index a920ba03cbf..f53031b707c 100644 --- a/packages/eslint-plugin/docs/rules/no-misused-new.md +++ b/packages/eslint-plugin/docs/rules/no-misused-new.md @@ -4,7 +4,11 @@ Warns on apparent attempts to define constructors for interfaces or `new` for cl ## Rule Details -Examples of **incorrect** code for this rule. +Examples of code for this rule: + + + +### ❌ Incorrect ```ts class C { @@ -17,7 +21,7 @@ interface I { } ``` -Examples of **correct** code for this rule. +### ✅ Correct ```ts class C { diff --git a/packages/eslint-plugin/docs/rules/no-misused-promises.md b/packages/eslint-plugin/docs/rules/no-misused-promises.md index 7e4f28170a6..78317d96b8c 100644 --- a/packages/eslint-plugin/docs/rules/no-misused-promises.md +++ b/packages/eslint-plugin/docs/rules/no-misused-promises.md @@ -7,7 +7,63 @@ functions are handled/awaited. ## Rule Details -Examples of **incorrect** code for this rule with `checksConditionals: true`: +This rule accepts a single option which is an object with `checksConditionals` +and `checksVoidReturn` properties indicating which types of misuse to flag. +Both are enabled by default + +## Options + +```ts +type Options = [ + { + checksConditionals?: boolean; + checksVoidReturn?: boolean; + }, +]; + +const defaultOptions: Options = [ + { + checksConditionals: true, + checksVoidReturn: true, + }, +]; +``` + +If you don't want functions that return promises where a void return is +expected to be checked, your configuration will look like this: + +```json +{ + "@typescript-eslint/no-misused-promises": [ + "error", + { + "checksVoidReturn": false + } + ] +} +``` + +Likewise, if you don't want to check conditionals, you can configure the rule +like this: + +```json +{ + "@typescript-eslint/no-misused-promises": [ + "error", + { + "checksConditionals": false + } + ] +} +``` + +### `checksConditionals: true` + +Examples of code for this rule with `checksConditionals: true`: + + + +#### ❌ Incorrect ```ts const promise = Promise.resolve('value'); @@ -23,7 +79,7 @@ while (promise) { } ``` -Examples of **correct** code with `checksConditionals: true`: +#### ✅ Correct ```ts const promise = Promise.resolve('value'); @@ -40,9 +96,15 @@ while (await promise) { } ``` ---- + + +### `checksVoidReturn: true` + +Examples of code for this rule with `checksVoidReturn: true`: + + -Examples of **incorrect** code for this rule with `checksVoidReturn: true`: +#### ❌ Incorrect ```ts [1, 2, 3].forEach(async value => { @@ -62,7 +124,7 @@ eventEmitter.on('some-event', async () => { }); ``` -Examples of **correct** code with `checksVoidReturn: true`: +#### ✅ Correct ```ts // for-of puts `await` in outer context @@ -104,39 +166,7 @@ eventEmitter.on('some-event', () => { }); ``` -## Options - -This rule accepts a single option which is an object with `checksConditionals` -and `checksVoidReturn` properties indicating which types of misuse to flag. -Both are enabled by default - -If you don't want functions that return promises where a void return is -expected to be checked, your configuration will look like this: - -```json -{ - "@typescript-eslint/no-misused-promises": [ - "error", - { - "checksVoidReturn": false - } - ] -} -``` - -Likewise, if you don't want to check conditionals, you can configure the rule -like this: - -```json -{ - "@typescript-eslint/no-misused-promises": [ - "error", - { - "checksConditionals": false - } - ] -} -``` + ## When Not To Use It diff --git a/packages/eslint-plugin/docs/rules/no-namespace.md b/packages/eslint-plugin/docs/rules/no-namespace.md index 465dd58b3e0..e044df82159 100644 --- a/packages/eslint-plugin/docs/rules/no-namespace.md +++ b/packages/eslint-plugin/docs/rules/no-namespace.md @@ -18,7 +18,11 @@ or more of the following you may pass an object with the options set as follows: - `allowDefinitionFiles` set to `true` will allow you to `declare` and use custom TypeScript modules and namespaces inside definition files (Default: `true`). -Examples of **incorrect** code for the default `{ "allowDeclarations": false, "allowDefinitionFiles": true }` options: +Examples of code for the default `{ "allowDeclarations": false, "allowDefinitionFiles": true }` options: + + + +### ❌ Incorrect ```ts module foo {} @@ -28,7 +32,7 @@ declare module foo {} declare namespace foo {} ``` -Examples of **correct** code for the default `{ "allowDeclarations": false, "allowDefinitionFiles": true }` options: +### ✅ Correct ```ts declare module 'foo' {} @@ -36,16 +40,22 @@ declare module 'foo' {} // anything inside a d.ts file ``` + + ### `allowDeclarations` -Examples of **incorrect** code for the `{ "allowDeclarations": true }` option: +Examples of code for the `{ "allowDeclarations": true }` option: + + + +#### ❌ Incorrect ```ts module foo {} namespace foo {} ``` -Examples of **correct** code for the `{ "allowDeclarations": true }` option: +#### ✅ Correct ```ts declare module 'foo' {} @@ -61,7 +71,13 @@ declare module foo { } ``` -Examples of **incorrect** code for the `{ "allowDeclarations": false }` option: + + +Examples of code for the `{ "allowDeclarations": false }` option: + + + +#### ❌ Incorrect ```ts module foo {} @@ -70,7 +86,7 @@ declare module foo {} declare namespace foo {} ``` -Examples of **correct** code for the `{ "allowDeclarations": false }` option: +#### ✅ Correct ```ts declare module 'foo' {} @@ -78,7 +94,11 @@ declare module 'foo' {} ### `allowDefinitionFiles` -Examples of **incorrect** code for the `{ "allowDefinitionFiles": true }` option: +Examples of code for the `{ "allowDefinitionFiles": true }` option: + + + +#### ❌ Incorrect ```ts // if outside a d.ts file @@ -92,7 +112,7 @@ declare module foo {} declare namespace foo {} ``` -Examples of **correct** code for the `{ "allowDefinitionFiles": true }` option: +#### ✅ Correct ```ts declare module 'foo' {} diff --git a/packages/eslint-plugin/docs/rules/no-non-null-asserted-nullish-coalescing.md b/packages/eslint-plugin/docs/rules/no-non-null-asserted-nullish-coalescing.md index 2eb8ff2585d..498ac053d6f 100644 --- a/packages/eslint-plugin/docs/rules/no-non-null-asserted-nullish-coalescing.md +++ b/packages/eslint-plugin/docs/rules/no-non-null-asserted-nullish-coalescing.md @@ -5,7 +5,11 @@ The nullish coalescing operator is designed to provide a default value when dealing with `null` or `undefined`. Using non-null assertions in the left operand of the nullish coalescing operator is redundant. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts /* eslint @typescript-eslint/no-non-null-asserted-nullish-coalescing: "error" */ @@ -23,7 +27,7 @@ x = foo(); x! ?? ''; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /* eslint @typescript-eslint/no-non-null-asserted-nullish-coalescing: "error" */ diff --git a/packages/eslint-plugin/docs/rules/no-non-null-asserted-optional-chain.md b/packages/eslint-plugin/docs/rules/no-non-null-asserted-optional-chain.md index 16a22b48035..0a59902883d 100644 --- a/packages/eslint-plugin/docs/rules/no-non-null-asserted-optional-chain.md +++ b/packages/eslint-plugin/docs/rules/no-non-null-asserted-optional-chain.md @@ -5,7 +5,11 @@ Optional chain expressions are designed to return `undefined` if the optional property is nullish. Using non-null assertions after an optional chain expression is wrong, and introduces a serious type safety hole into your code. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts /* eslint @typescript-eslint/no-non-null-asserted-optional-chain: "error" */ @@ -21,7 +25,7 @@ foo?.bar!(); foo?.bar!().baz; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /* eslint @typescript-eslint/no-non-null-asserted-optional-chain: "error" */ diff --git a/packages/eslint-plugin/docs/rules/no-non-null-assertion.md b/packages/eslint-plugin/docs/rules/no-non-null-assertion.md index 1eaebff625c..cbd76d1bb1f 100644 --- a/packages/eslint-plugin/docs/rules/no-non-null-assertion.md +++ b/packages/eslint-plugin/docs/rules/no-non-null-assertion.md @@ -4,7 +4,11 @@ Using non-null assertions cancels the benefits of the strict null-checking mode. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts interface Foo { @@ -15,7 +19,7 @@ const foo: Foo = getFoo(); const includesBaz: boolean = foo.bar!.includes('baz'); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts interface Foo { diff --git a/packages/eslint-plugin/docs/rules/no-parameter-properties.md b/packages/eslint-plugin/docs/rules/no-parameter-properties.md index 6bde9296b5b..bea03258575 100644 --- a/packages/eslint-plugin/docs/rules/no-parameter-properties.md +++ b/packages/eslint-plugin/docs/rules/no-parameter-properties.md @@ -24,7 +24,11 @@ If you would like to allow certain types of parameter properties then you may pa ### default -Examples of **incorrect** code for this rule with no options at all: +Examples of code for this rule with no options at all: + + + +#### ❌ Incorrect ```ts class Foo { @@ -56,7 +60,7 @@ class Foo { } ``` -Examples of **correct** code for this rule with no options at all: +#### ✅ Correct ```ts class Foo { @@ -66,7 +70,11 @@ class Foo { ### readonly -Examples of **incorrect** code for the `{ "allows": ["readonly"] }` options: +Examples of code for the `{ "allows": ["readonly"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -94,7 +102,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["readonly"] }` options: +#### ✅ Correct ```ts class Foo { @@ -108,7 +116,11 @@ class Foo { ### private -Examples of **incorrect** code for the `{ "allows": ["private"] }` options: +Examples of code for the `{ "allows": ["private"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -136,7 +148,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["private"] }` options: +#### ✅ Correct ```ts class Foo { @@ -150,7 +162,11 @@ class Foo { ### protected -Examples of **incorrect** code for the `{ "allows": ["protected"] }` options: +Examples of code for the `{ "allows": ["protected"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -178,7 +194,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["protected"] }` options: +#### ✅ Correct ```ts class Foo { @@ -192,7 +208,11 @@ class Foo { ### public -Examples of **incorrect** code for the `{ "allows": ["public"] }` options: +Examples of code for the `{ "allows": ["public"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -220,7 +240,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["public"] }` options: +#### ✅ Correct ```ts class Foo { @@ -234,7 +254,11 @@ class Foo { ### private readonly -Examples of **incorrect** code for the `{ "allows": ["private readonly"] }` options: +Examples of code for the `{ "allows": ["private readonly"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -262,7 +286,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["private readonly"] }` options: +#### ✅ Correct ```ts class Foo { @@ -276,7 +300,11 @@ class Foo { ### protected readonly -Examples of **incorrect** code for the `{ "allows": ["protected readonly"] }` options: +Examples of code for the `{ "allows": ["protected readonly"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -304,7 +332,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["protected readonly"] }` options: +#### ✅ Correct ```ts class Foo { @@ -318,7 +346,11 @@ class Foo { ### public readonly -Examples of **incorrect** code for the `{ "allows": ["public readonly"] }` options: +Examples of code for the `{ "allows": ["public readonly"] }` options: + + + +#### ❌ Incorrect ```ts class Foo { @@ -346,7 +378,7 @@ class Foo { } ``` -Examples of **correct** code for the `{ "allows": ["public readonly"] }` options: +#### ✅ Correct ```ts class Foo { diff --git a/packages/eslint-plugin/docs/rules/no-require-imports.md b/packages/eslint-plugin/docs/rules/no-require-imports.md index 2bc3eca93f9..69f466f24b8 100644 --- a/packages/eslint-plugin/docs/rules/no-require-imports.md +++ b/packages/eslint-plugin/docs/rules/no-require-imports.md @@ -4,7 +4,11 @@ Prefer the newer ES6-style imports over `require()`. ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts var lib = require('lib'); @@ -14,7 +18,7 @@ var lib5 = require('lib5'), import lib8 = require('lib8'); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts import { l } from 'lib'; diff --git a/packages/eslint-plugin/docs/rules/no-restricted-imports.md b/packages/eslint-plugin/docs/rules/no-restricted-imports.md index 359cfd4f084..73a2f95824c 100644 --- a/packages/eslint-plugin/docs/rules/no-restricted-imports.md +++ b/packages/eslint-plugin/docs/rules/no-restricted-imports.md @@ -41,19 +41,11 @@ You can specify this option for a specific path or pattern as follows: When set to `true`, the rule will allow [Type-Only Imports](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export). -Examples of **correct** code with the above config: +Examples of code with the above config: -```ts -import { foo } from 'other-module'; - -import type foo from 'import-foo'; -export type { Foo } from 'import-foo'; + -import type baz from 'import-baz'; -export type { Baz } from 'import-baz'; -``` - -Example of **incorrect** code with the above config: +#### ❌ Incorrect ```ts import foo from 'import-foo'; @@ -63,6 +55,18 @@ import baz from 'import-baz'; export { Baz } from 'import-baz'; ``` +#### ✅ Correct + +```ts +import { foo } from 'other-module'; + +import type foo from 'import-foo'; +export type { Foo } from 'import-foo'; + +import type baz from 'import-baz'; +export type { Baz } from 'import-baz'; +``` + ## Attributes - [ ] ✅ Recommended diff --git a/packages/eslint-plugin/docs/rules/no-this-alias.md b/packages/eslint-plugin/docs/rules/no-this-alias.md index 67cb36df2e4..2ae9859316d 100644 --- a/packages/eslint-plugin/docs/rules/no-this-alias.md +++ b/packages/eslint-plugin/docs/rules/no-this-alias.md @@ -35,7 +35,7 @@ Examples of **correct** code for this rule: (see the rationale above) -### Options +## Options You can pass an object option: diff --git a/packages/eslint-plugin/docs/rules/no-throw-literal.md b/packages/eslint-plugin/docs/rules/no-throw-literal.md index cd711ced9f6..e9077cd4cfc 100644 --- a/packages/eslint-plugin/docs/rules/no-throw-literal.md +++ b/packages/eslint-plugin/docs/rules/no-throw-literal.md @@ -9,7 +9,11 @@ This rule restricts what can be thrown as an exception. When it was first create This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an `Error` object. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts /*eslint @typescript-eslint/no-throw-literal: "error"*/ @@ -42,7 +46,7 @@ const foo = { throw foo.bar; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /*eslint @typescript-eslint/no-throw-literal: "error"*/ diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-boolean-literal-compare.md b/packages/eslint-plugin/docs/rules/no-unnecessary-boolean-literal-compare.md index f39f663ddfb..a3c7d6f8b6b 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-boolean-literal-compare.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-boolean-literal-compare.md @@ -18,7 +18,11 @@ distinguish between strict and loose equality. Any example below that uses `===` would be treated the same way if `==` was used, and any example below that uses `!==` would be treated the same way if `!=` was used. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts declare const someCondition: boolean; @@ -26,7 +30,7 @@ if (someCondition === true) { } ``` -Examples of **correct** code for this rule +### ✅ Correct ```ts declare const someCondition: boolean; @@ -70,7 +74,11 @@ const defaults = { ### `allowComparingNullableBooleansToTrue` -Examples of **incorrect** code for this rule with `{ allowComparingNullableBooleansToTrue: false }`: +Examples of code for this rule with `{ allowComparingNullableBooleansToTrue: false }`: + + + +#### ❌ Incorrect ```ts declare const someUndefinedCondition: boolean | undefined; @@ -82,7 +90,7 @@ if (someNullCondition !== true) { } ``` -Examples of **correct** code for this rule with `{ allowComparingNullableBooleansToTrue: false }`: +#### ✅ Correct ```ts declare const someUndefinedCondition: boolean | undefined; @@ -96,7 +104,11 @@ if (!someNullCondition) { ### `allowComparingNullableBooleansToFalse` -Examples of **incorrect** code for this rule with `{ allowComparingNullableBooleansToFalse: false }`: +Examples of code for this rule with `{ allowComparingNullableBooleansToFalse: false }`: + + + +#### ❌ Incorrect ```ts declare const someUndefinedCondition: boolean | undefined; @@ -108,7 +120,7 @@ if (someNullCondition !== false) { } ``` -Examples of **correct** code for this rule with `{ allowComparingNullableBooleansToFalse: false }`: +#### ✅ Correct ```ts declare const someUndefinedCondition: boolean | undefined; diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md b/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md index 0dda0b0d8b2..cb6be06e137 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md @@ -8,7 +8,13 @@ The following expressions are checked: - Conditions for `if`, `for`, `while`, and `do-while` statements - Base values of optional chain expressions -Examples of **incorrect** code for this rule: +## Rule Details + +Examples of code for this rule: + + + +### ❌ Incorrect ```ts function head(items: T[]) { @@ -36,7 +42,7 @@ function bar(arg: string) { ].filter(t => t); // number[] is always truthy ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts function head(items: T[]) { diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-qualifier.md b/packages/eslint-plugin/docs/rules/no-unnecessary-qualifier.md index 2983307bbdb..d1425d836ab 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-qualifier.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-qualifier.md @@ -5,7 +5,11 @@ This rule aims to let users know when a namespace or enum qualifier is unnecessary, whether used for a type or for a value. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts namespace A { @@ -37,7 +41,7 @@ namespace A { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts namespace X { diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-type-arguments.md b/packages/eslint-plugin/docs/rules/no-unnecessary-type-arguments.md index 83d1041974d..cab4a10ea0a 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-type-arguments.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-type-arguments.md @@ -13,7 +13,11 @@ function f() {} It is redundant to provide an explicit type parameter equal to that default. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts function f() {} @@ -31,7 +35,7 @@ interface I {} class Impl implements I {} ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts function f() {} diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md b/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md index cfca8f20b1c..b969d13d28c 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-type-assertion.md @@ -6,7 +6,11 @@ This rule prohibits using a type assertion that does not change the type of an e This rule aims to prevent unnecessary type assertions. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const foo = 3; @@ -33,7 +37,7 @@ function foo(x: number): number { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts const foo = 3; @@ -53,7 +57,7 @@ function foo(x: number | undefined): number { } ``` -### Options +## Options This rule optionally takes an object with a single property `typesToIgnore`, which can be set to a list of type names to ignore. diff --git a/packages/eslint-plugin/docs/rules/no-unnecessary-type-constraint.md b/packages/eslint-plugin/docs/rules/no-unnecessary-type-constraint.md index dd0d5025f9a..b69dab2c157 100644 --- a/packages/eslint-plugin/docs/rules/no-unnecessary-type-constraint.md +++ b/packages/eslint-plugin/docs/rules/no-unnecessary-type-constraint.md @@ -10,7 +10,11 @@ When not provided, type parameters happen to default to: It is therefore redundant to `extend` from these types in later versions of TypeScript. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts interface FooAny {} @@ -34,7 +38,7 @@ function QuuzAny() {} function QuuzUnknown() {} ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts interface Foo {} diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-argument.md b/packages/eslint-plugin/docs/rules/no-unsafe-argument.md index a197ff65cab..de0ff8e0e01 100644 --- a/packages/eslint-plugin/docs/rules/no-unsafe-argument.md +++ b/packages/eslint-plugin/docs/rules/no-unsafe-argument.md @@ -9,7 +9,11 @@ This rule disallows calling a function with `any` in its arguments, and it will This rule also disallows spreading a tuple type with one of its elements typed as `any`. This rule also compares the argument's type to the variable's type to ensure you don't pass an unsafe `any` in a generic position to a receiver that's expecting a specific type. For example, it will error if you assign `Set` to an argument declared as `Set`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts declare function foo(arg1: string, arg2: number, arg2: string): void; @@ -36,7 +40,7 @@ declare function baz(arg1: Set, arg2: Map): void; foo(new Set(), new Map()); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts declare function foo(arg1: string, arg2: number, arg2: string): void; @@ -54,6 +58,8 @@ declare function baz(arg1: Set, arg2: Map): void; foo(new Set(), new Map()); ``` + + There are cases where the rule allows passing an argument of `any` to `unknown`. Example of `any` to `unknown` assignment that are allowed. diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md b/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md index 36542927eed..9416c260ed9 100644 --- a/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md +++ b/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md @@ -8,7 +8,11 @@ Assigning an `any` typed value to a variable can be hard to pick up on, particul This rule disallows assigning `any` to a variable, and assigning `any[]` to an array destructuring. This rule also compares the assigned type to the variable's type to ensure you don't assign an unsafe `any` in a generic position to a receiver that's expecting a specific type. For example, it will error if you assign `Set` to a variable declared as `Set`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const x = 1 as any, @@ -33,7 +37,7 @@ const x: Set = new Set(); const x: Set>> = new Set>>(); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts const x = 1, @@ -56,6 +60,8 @@ const x: Set = new Set(); const x: Set>> = new Set>>(); ``` + + There are cases where the rule allows assignment of `any` to `unknown`. Example of `any` to `unknown` assignment that are allowed. diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-call.md b/packages/eslint-plugin/docs/rules/no-unsafe-call.md index 0dfb019bbae..9279d1cf4be 100644 --- a/packages/eslint-plugin/docs/rules/no-unsafe-call.md +++ b/packages/eslint-plugin/docs/rules/no-unsafe-call.md @@ -7,7 +7,11 @@ The arguments to, and return value of calling an `any` typed variable are not ch This rule disallows calling any variable that is typed as `any`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts declare const anyVar: any; @@ -26,7 +30,7 @@ anyVar`foo`; nestedAny.prop`foo`; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts declare const typedVar: () => void; diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-member-access.md b/packages/eslint-plugin/docs/rules/no-unsafe-member-access.md index 39c982d5deb..57835e3e9a4 100644 --- a/packages/eslint-plugin/docs/rules/no-unsafe-member-access.md +++ b/packages/eslint-plugin/docs/rules/no-unsafe-member-access.md @@ -7,7 +7,11 @@ Member access on `any` typed variables is not checked at all by TypeScript, so i This rule disallows member access on any variable that is typed as `any`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts declare const anyVar: any; @@ -30,7 +34,7 @@ arr[anyVar]; nestedAny[anyVar]; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts declare const properlyTyped: { prop: { a: string } }; diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-return.md b/packages/eslint-plugin/docs/rules/no-unsafe-return.md index e089757a177..40e20810966 100644 --- a/packages/eslint-plugin/docs/rules/no-unsafe-return.md +++ b/packages/eslint-plugin/docs/rules/no-unsafe-return.md @@ -8,7 +8,11 @@ Returned `any` typed values are not checked at all by TypeScript, so it creates This rule disallows returning `any` or `any[]` from a function. This rule also compares the return type to the function's declared/inferred return type to ensure you don't return an unsafe `any` in a generic position to a receiver that's expecting a specific type. For example, it will error if you return `Set` from a function declared as returning `Set`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts function foo1() { @@ -49,7 +53,7 @@ type TAssign = () => Set; const assignability2: TAssign = () => new Set([true]); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts function foo1() { @@ -69,6 +73,8 @@ type TAssign = () => Set; const assignability2: TAssign = () => new Set(['foo']); ``` + + There are cases where the rule allows to return `any` to `unknown`. Examples of `any` to `unknown` return that are allowed. diff --git a/packages/eslint-plugin/docs/rules/no-use-before-define.md b/packages/eslint-plugin/docs/rules/no-use-before-define.md index 83069ce0558..e155e3e3f9d 100644 --- a/packages/eslint-plugin/docs/rules/no-use-before-define.md +++ b/packages/eslint-plugin/docs/rules/no-use-before-define.md @@ -40,7 +40,11 @@ const defaultOptions: Options = { If this is `true`, this rule warns every reference to a enum before the enum declaration. If this is `false`, this rule will ignore references to enums, when the reference is in a child scope. -Examples of **incorrect** code for the `{ "enums": true }` option: +Examples of code for the `{ "enums": true }` option: + + + +#### ❌ Incorrect ```ts /*eslint no-use-before-define: ["error", { "enums": true }]*/ @@ -52,7 +56,7 @@ enum Foo { } ``` -Examples of **correct** code for the `{ "enums": false }` option: +#### ✅ Correct ```ts /*eslint no-use-before-define: ["error", { "enums": false }]*/ diff --git a/packages/eslint-plugin/docs/rules/no-var-requires.md b/packages/eslint-plugin/docs/rules/no-var-requires.md index 19373a89283..58b8544bd5f 100644 --- a/packages/eslint-plugin/docs/rules/no-var-requires.md +++ b/packages/eslint-plugin/docs/rules/no-var-requires.md @@ -4,7 +4,11 @@ In other words, the use of forms such as `var foo = require("foo")` are banned. ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts var foo = require('foo'); @@ -12,7 +16,7 @@ const foo = require('foo'); let foo = require('foo'); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts import foo = require('foo'); diff --git a/packages/eslint-plugin/docs/rules/non-nullable-type-assertion-style.md b/packages/eslint-plugin/docs/rules/non-nullable-type-assertion-style.md index a152ee12205..f4fe4320f9d 100644 --- a/packages/eslint-plugin/docs/rules/non-nullable-type-assertion-style.md +++ b/packages/eslint-plugin/docs/rules/non-nullable-type-assertion-style.md @@ -4,7 +4,11 @@ This rule detects when an `as` cast is doing the same job as a `!` would, and su ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const maybe = Math.random() > 0.5 ? '' : undefined; @@ -13,7 +17,7 @@ const definitely = maybe as string; const alsoDefinitely = maybe; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts const maybe = Math.random() > 0.5 ? '' : undefined; diff --git a/packages/eslint-plugin/docs/rules/prefer-as-const.md b/packages/eslint-plugin/docs/rules/prefer-as-const.md index 94c21dac9d0..e873bb5a1f7 100644 --- a/packages/eslint-plugin/docs/rules/prefer-as-const.md +++ b/packages/eslint-plugin/docs/rules/prefer-as-const.md @@ -4,7 +4,11 @@ This rule recommends usage of `const` assertion when type primitive value is equ ## Rule Details -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts let bar: 2 = 2; @@ -12,7 +16,7 @@ let foo = <'bar'>'bar'; let foo = { bar: 'baz' as 'baz' }; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts let foo = 'bar'; @@ -23,6 +27,8 @@ let foo = 'bar'; let foo = { bar: 'baz' }; ``` + + ## When Not To Use It If you are using TypeScript < 3.4 diff --git a/packages/eslint-plugin/docs/rules/prefer-enum-initializers.md b/packages/eslint-plugin/docs/rules/prefer-enum-initializers.md index b7aeb21a772..7baefc1b65e 100644 --- a/packages/eslint-plugin/docs/rules/prefer-enum-initializers.md +++ b/packages/eslint-plugin/docs/rules/prefer-enum-initializers.md @@ -25,7 +25,11 @@ enum Status { } ``` -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts enum Status { @@ -45,7 +49,7 @@ enum Color { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts enum Status { diff --git a/packages/eslint-plugin/docs/rules/prefer-for-of.md b/packages/eslint-plugin/docs/rules/prefer-for-of.md index 919531136a4..86b7134aa78 100644 --- a/packages/eslint-plugin/docs/rules/prefer-for-of.md +++ b/packages/eslint-plugin/docs/rules/prefer-for-of.md @@ -6,7 +6,11 @@ This rule recommends a for-of loop when the loop index is only used to read from For cases where the index is only used to read from the array being iterated, a for-of loop is easier to read and write. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```js for (let i = 0; i < arr.length; i++) { @@ -14,7 +18,7 @@ for (let i = 0; i < arr.length; i++) { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```js for (const x of arr) { diff --git a/packages/eslint-plugin/docs/rules/prefer-function-type.md b/packages/eslint-plugin/docs/rules/prefer-function-type.md index 007f3baa01a..c67a61bfa5e 100644 --- a/packages/eslint-plugin/docs/rules/prefer-function-type.md +++ b/packages/eslint-plugin/docs/rules/prefer-function-type.md @@ -4,7 +4,11 @@ This rule suggests using a function type instead of an interface or object type literal with a single call signature. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts interface Foo { @@ -31,7 +35,7 @@ interface MixinMethod { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts interface Foo { diff --git a/packages/eslint-plugin/docs/rules/prefer-includes.md b/packages/eslint-plugin/docs/rules/prefer-includes.md index 29c37563fd4..57eb97b271f 100644 --- a/packages/eslint-plugin/docs/rules/prefer-includes.md +++ b/packages/eslint-plugin/docs/rules/prefer-includes.md @@ -15,7 +15,11 @@ There are such types: `String`, `Array`, `ReadonlyArray`, and typed arrays. Additionally, this rule reports the tests of simple regular expressions in favor of `String#includes`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts let str: string; @@ -39,7 +43,7 @@ userDefined.indexOf(value) >= 0; /foo/.test(str); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts let array: any[]; diff --git a/packages/eslint-plugin/docs/rules/prefer-literal-enum-member.md b/packages/eslint-plugin/docs/rules/prefer-literal-enum-member.md index 94891c46235..eb952dfd407 100644 --- a/packages/eslint-plugin/docs/rules/prefer-literal-enum-member.md +++ b/packages/eslint-plugin/docs/rules/prefer-literal-enum-member.md @@ -25,7 +25,11 @@ This rule is meant to prevent unexpected results in code by requiring the use of - `allowBitwiseExpressions` set to `true` will allow you to use bitwise expressions in enum initializer (Default: `false`). -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const str = 'Test'; @@ -38,7 +42,7 @@ enum Invalid { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts enum Valid { @@ -50,9 +54,15 @@ enum Valid { } ``` + + ### `allowBitwiseExpressions` -Examples of **incorrect** code for the `{ "allowBitwiseExpressions": true }` option: +Examples of code for the `{ "allowBitwiseExpressions": true }` option: + + + +#### ❌ Incorrect ```ts const x = 1; @@ -67,7 +77,7 @@ enum Foo { } ``` -Examples of **correct** code for the `{ "allowBitwiseExpressions": true }` option: +#### ✅ Correct ```ts enum Foo { diff --git a/packages/eslint-plugin/docs/rules/prefer-optional-chain.md b/packages/eslint-plugin/docs/rules/prefer-optional-chain.md index 22c596b4375..179ba988733 100644 --- a/packages/eslint-plugin/docs/rules/prefer-optional-chain.md +++ b/packages/eslint-plugin/docs/rules/prefer-optional-chain.md @@ -44,7 +44,11 @@ Because the optional chain operator _only_ chains when the property value is `nu This rule aims enforce the usage of the safer operator. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts foo && foo.a && foo.a.b && foo.a.b.c; @@ -60,7 +64,7 @@ foo && foo.a.b.c.d.e; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts foo?.a?.b?.c; diff --git a/packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md b/packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md index b6a57c4b069..6790b55113e 100644 --- a/packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md +++ b/packages/eslint-plugin/docs/rules/prefer-readonly-parameter-types.md @@ -15,7 +15,11 @@ A type is considered readonly if: - it is a readonly tuple type whose elements are all considered readonly. - it is an object type whose properties are all marked as readonly, and whose values are all considered readonly. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts function array1(arg: string[]) {} // array is not readonly @@ -57,7 +61,7 @@ interface Foo { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts function array1(arg: readonly string[]) {} @@ -139,7 +143,11 @@ const defaultOptions: Options = { This option allows you to enable or disable the checking of parameter properties. Because parameter properties create properties on the class, it may be undesirable to force them to be readonly. -Examples of **incorrect** code for this rule with `{checkParameterProperties: true}`: +Examples of code for this rule with `{checkParameterProperties: true}`: + + + +#### ❌ Incorrect ```ts class Foo { @@ -147,7 +155,7 @@ class Foo { } ``` -Examples of **correct** code for this rule with `{checkParameterProperties: true}`: +#### ✅ Correct ```ts class Foo { @@ -155,6 +163,8 @@ class Foo { } ``` + + Examples of **correct** code for this rule with `{checkParameterProperties: false}`: ```ts @@ -170,7 +180,11 @@ class Foo { This option allows you to ignore parameters which don't explicitly specify a type. This may be desirable in cases where an external dependency specifies a callback with mutable parameters, and manually annotating the callback's parameters is undesirable. -Examples of **incorrect** code for this rule with `{ignoreInferredTypes: true}`: +Examples of code for this rule with `{ignoreInferredTypes: true}`: + + + +#### ❌ Incorrect ```ts import { acceptsCallback, CallbackOptions } from 'external-dependency'; @@ -193,7 +207,7 @@ export const acceptsCallback: AcceptsCallback; -Examples of **correct** code for this rule with `{ignoreInferredTypes: true}`: +#### ✅ Correct ```ts import { acceptsCallback } from 'external-dependency'; @@ -220,7 +234,11 @@ export const acceptsCallback: AcceptsCallback; This option allows you to treat all mutable methods as though they were readonly. This may be desirable in when you are never reassigning methods. -Examples of **incorrect** code for this rule with `{treatMethodsAsReadonly: false}`: +Examples of code for this rule with `{treatMethodsAsReadonly: false}`: + + + +#### ❌ Incorrect ```ts type MyType = { @@ -230,7 +248,7 @@ type MyType = { function foo(arg: MyType) {} ``` -Examples of **correct** code for this rule with `{treatMethodsAsReadonly: false}`: +#### ✅ Correct ```ts type MyType = Readonly<{ @@ -246,6 +264,8 @@ type MyOtherType = { function bar(arg: MyOtherType) {} ``` + + Examples of **correct** code for this rule with `{treatMethodsAsReadonly: true}`: ```ts diff --git a/packages/eslint-plugin/docs/rules/prefer-readonly.md b/packages/eslint-plugin/docs/rules/prefer-readonly.md index df41adb8c83..ab36071199b 100644 --- a/packages/eslint-plugin/docs/rules/prefer-readonly.md +++ b/packages/eslint-plugin/docs/rules/prefer-readonly.md @@ -7,7 +7,11 @@ This rule enforces that private members are marked as `readonly` if they're neve Member variables with the privacy `private` are never permitted to be modified outside of their declaring class. If that class never modifies their value, they may safely be marked as `readonly`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts class Container { @@ -25,7 +29,7 @@ class Container { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts class Container { @@ -58,21 +62,23 @@ You may pass `"onlyInlineLambdas": true` as a rule option within an object to re } ``` -Example of **correct** code for the `{ "onlyInlineLambdas": true }` options: +Example of code for the `{ "onlyInlineLambdas": true }` options: + +#### ❌ Incorrect ```ts class Container { - private neverModifiedPrivate = 'unchanged'; + private onClick = () => { + /* ... */ + }; } ``` -Example of **incorrect** code for the `{ "onlyInlineLambdas": true }` options: +#### ✅ Correct ```ts class Container { - private onClick = () => { - /* ... */ - }; + private neverModifiedPrivate = 'unchanged'; } ``` diff --git a/packages/eslint-plugin/docs/rules/prefer-reduce-type-parameter.md b/packages/eslint-plugin/docs/rules/prefer-reduce-type-parameter.md index 04bd5803a4a..8ad9d675b53 100644 --- a/packages/eslint-plugin/docs/rules/prefer-reduce-type-parameter.md +++ b/packages/eslint-plugin/docs/rules/prefer-reduce-type-parameter.md @@ -17,7 +17,11 @@ This means that TypeScript doesn't have to try to infer the type, and avoids the This rule looks for calls to `Array#reduce`, and warns if an initial value is being passed & casted, suggesting instead to pass the cast type to `Array#reduce` as its generic parameter. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts [1, 2, 3].reduce((arr, num) => arr.concat(num * 2), [] as number[]); @@ -31,7 +35,7 @@ Examples of **incorrect** code for this rule: ); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts [1, 2, 3].reduce((arr, num) => arr.concat(num * 2), []); diff --git a/packages/eslint-plugin/docs/rules/prefer-regexp-exec.md b/packages/eslint-plugin/docs/rules/prefer-regexp-exec.md index 32209cf731c..138ab1c1ded 100644 --- a/packages/eslint-plugin/docs/rules/prefer-regexp-exec.md +++ b/packages/eslint-plugin/docs/rules/prefer-regexp-exec.md @@ -12,7 +12,11 @@ From [`String#match` on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaSc `RegExp#exec` may also be slightly faster than `String#match`; this is the reason to choose it as the preferred usage. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts 'something'.match(/thing/); @@ -24,7 +28,7 @@ const search = /thing/; text.match(search); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts /thing/.exec('something'); diff --git a/packages/eslint-plugin/docs/rules/prefer-return-this-type.md b/packages/eslint-plugin/docs/rules/prefer-return-this-type.md index c61c462889f..acc8520a97d 100644 --- a/packages/eslint-plugin/docs/rules/prefer-return-this-type.md +++ b/packages/eslint-plugin/docs/rules/prefer-return-this-type.md @@ -43,7 +43,13 @@ const cat = new Cat(); cat.eat().meow(); ``` -Examples of **incorrect** code for this rule: +## Rule Details + +Examples of code for this rule: + + + +### ❌ Incorrect ```ts class Foo { @@ -59,7 +65,7 @@ class Foo { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts class Foo { diff --git a/packages/eslint-plugin/docs/rules/prefer-string-starts-ends-with.md b/packages/eslint-plugin/docs/rules/prefer-string-starts-ends-with.md index 0979653f856..d67c7bd7d7e 100644 --- a/packages/eslint-plugin/docs/rules/prefer-string-starts-ends-with.md +++ b/packages/eslint-plugin/docs/rules/prefer-string-starts-ends-with.md @@ -8,7 +8,11 @@ Since ES2015 has added `String#startsWith` and `String#endsWith`, this rule repo This rule is aimed at enforcing a consistent way to check whether a string starts or ends with a specific string. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts let foo: string; @@ -32,7 +36,7 @@ foo.match(/bar$/) != null; /bar$/.test(foo); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts foo.startsWith('bar'); diff --git a/packages/eslint-plugin/docs/rules/prefer-ts-expect-error.md b/packages/eslint-plugin/docs/rules/prefer-ts-expect-error.md index 2ae69fe7d19..faf22348aaa 100644 --- a/packages/eslint-plugin/docs/rules/prefer-ts-expect-error.md +++ b/packages/eslint-plugin/docs/rules/prefer-ts-expect-error.md @@ -14,7 +14,11 @@ This directive operates in the same manner as `@ts-ignore`, but will error if th This rule looks for usages of `@ts-ignore`, and flags them to be replaced with `@ts-expect-error`. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts // @ts-ignore @@ -35,7 +39,7 @@ const isOptionEnabled = (key: string): boolean => { }; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts // @ts-expect-error diff --git a/packages/eslint-plugin/docs/rules/promise-function-async.md b/packages/eslint-plugin/docs/rules/promise-function-async.md index 7638e6bc592..f587f6e5489 100644 --- a/packages/eslint-plugin/docs/rules/promise-function-async.md +++ b/packages/eslint-plugin/docs/rules/promise-function-async.md @@ -12,7 +12,11 @@ This rule's practice removes a requirement for creating code to handle both case ## Rule Details -Examples of **incorrect** code for this rule +Examples of code for this rule + + + +### ❌ Incorrect ```ts const arrowFunctionReturnsPromise = () => Promise.resolve('value'); @@ -22,7 +26,7 @@ function functionReturnsPromise() { } ``` -Examples of **correct** code for this rule +### ✅ Correct ```ts const arrowFunctionReturnsPromise = async () => Promise.resolve('value'); diff --git a/packages/eslint-plugin/docs/rules/require-array-sort-compare.md b/packages/eslint-plugin/docs/rules/require-array-sort-compare.md index f05bd66e9f5..87e7ed55285 100644 --- a/packages/eslint-plugin/docs/rules/require-array-sort-compare.md +++ b/packages/eslint-plugin/docs/rules/require-array-sort-compare.md @@ -23,7 +23,11 @@ https://www.ecma-international.org/ecma-262/9.0/#sec-sortcompare This rule aims to ensure all calls of the native `Array#sort` method provide a `compareFunction`, while ignoring calls to user-defined `sort` methods. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts const array: any[]; @@ -35,7 +39,7 @@ array.sort(); stringArray.sort(); ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts const array: any[]; @@ -66,7 +70,11 @@ const defaults = { ### `ignoreStringArrays` -Examples of **incorrect** code for this rule with `{ ignoreStringArrays: true }`: +Examples of code for this rule with `{ ignoreStringArrays: true }`: + + + +#### ❌ Incorrect ```ts const one = 1; @@ -75,7 +83,7 @@ const three = 3; [one, two, three].sort(); ``` -Examples of **correct** code for this rule with `{ ignoreStringArrays: true }`: +#### ✅ Correct ```ts const one = '1'; diff --git a/packages/eslint-plugin/docs/rules/restrict-plus-operands.md b/packages/eslint-plugin/docs/rules/restrict-plus-operands.md index 5299b734526..f5dca19d047 100644 --- a/packages/eslint-plugin/docs/rules/restrict-plus-operands.md +++ b/packages/eslint-plugin/docs/rules/restrict-plus-operands.md @@ -1,19 +1,25 @@ # When adding two variables, operands must both be of type number or of type string (`restrict-plus-operands`) -Examples of **correct** code: +## Rule Details -```ts -var foo = parseInt('5.5', 10) + 10; -var foo = 1n + 1n; -``` +Examples of code for this rule: -Examples of **incorrect** code: + + +### ❌ Incorrect ```ts var foo = '5.5' + 5; var foo = 1n + 1; ``` +### ✅ Correct + +```ts +var foo = parseInt('5.5', 10) + 10; +var foo = 1n + 1n; +``` + ## Options This rule has an object option: @@ -23,7 +29,11 @@ This rule has an object option: ### `checkCompoundAssignments` -Examples of **incorrect** code for the `{ "checkCompoundAssignments": true }` option: +Examples of code for the `{ "checkCompoundAssignments": true }` option: + + + +#### ❌ Incorrect ```ts /*eslint @typescript-eslint/restrict-plus-operands: ["error", { "checkCompoundAssignments": true }]*/ @@ -35,7 +45,7 @@ let bar: string = ''; bar += 0; ``` -Examples of **correct** code for the `{ "checkCompoundAssignments": true }` option: +#### ✅ Correct ```ts /*eslint @typescript-eslint/restrict-plus-operands: ["error", { "checkCompoundAssignments": true }]*/ @@ -47,6 +57,8 @@ let bar = ''; bar += 'test'; ``` +## How to use + ```json { "@typescript-eslint/restrict-plus-operands": "error" diff --git a/packages/eslint-plugin/docs/rules/restrict-template-expressions.md b/packages/eslint-plugin/docs/rules/restrict-template-expressions.md index d56eb6ae74b..771af5469e3 100644 --- a/packages/eslint-plugin/docs/rules/restrict-template-expressions.md +++ b/packages/eslint-plugin/docs/rules/restrict-template-expressions.md @@ -1,17 +1,12 @@ # Enforce template literal expressions to be of string type (`restrict-template-expressions`) -Examples of **correct** code: +## Rule Details -```ts -const arg = 'foo'; -const msg1 = `arg = ${arg}`; -const msg2 = `arg = ${arg || 'default'}`; +Examples of code for this rule: -const stringWithKindProp: string & { _kind?: 'MyString' } = 'foo'; -const msg3 = `stringWithKindProp = ${stringWithKindProp}`; -``` + -Examples of **incorrect** code: +### ❌ Incorrect ```ts const arg1 = [1, 2]; @@ -21,6 +16,17 @@ const arg2 = { name: 'Foo' }; const msg2 = `arg2 = ${arg2 || null}`; ``` +### ✅ Correct + +```ts +const arg = 'foo'; +const msg1 = `arg = ${arg}`; +const msg2 = `arg = ${arg || 'default'}`; + +const stringWithKindProp: string & { _kind?: 'MyString' } = 'foo'; +const msg3 = `stringWithKindProp = ${stringWithKindProp}`; +``` + ## Options The rule accepts an options object with the following properties: diff --git a/packages/eslint-plugin/docs/rules/return-await.md b/packages/eslint-plugin/docs/rules/return-await.md index df8813ff9c0..f28ee5d02c7 100644 --- a/packages/eslint-plugin/docs/rules/return-await.md +++ b/packages/eslint-plugin/docs/rules/return-await.md @@ -35,7 +35,11 @@ Specifically: - if you `return` a promise within a `catch`, and there **_is a_** `finally`, then it **_must_** be `await`ed. - if you `return` a promise within a `finally`, then it **_must not_** be `await`ed. -Examples of **incorrect** code with `in-try-catch`: +Examples of code with `in-try-catch`: + + + +#### ❌ Incorrect ```ts async function invalidInTryCatch1() { @@ -81,7 +85,7 @@ async function invalidInTryCatch6() { } ``` -Examples of **correct** code with `in-try-catch`: +#### ✅ Correct ```ts async function validInTryCatch1() { @@ -131,7 +135,11 @@ async function validInTryCatch6() { Requires that all returned promises are `await`ed. -Examples of **incorrect** code with `always`: +Examples of code with `always`: + + + +#### ❌ Incorrect ```ts async function invalidAlways1() { @@ -149,7 +157,7 @@ async function invalidAlways3() { } ``` -Examples of **correct** code with `always`: +#### ✅ Correct ```ts async function validAlways1() { @@ -171,7 +179,11 @@ async function validAlways3() { Disallows all `await`ing any returned promises. -Examples of **incorrect** code with `never`: +Examples of code with `never`: + + + +#### ❌ Incorrect ```ts async function invalidNever1() { @@ -189,7 +201,7 @@ async function invalidNever3() { } ``` -Examples of **correct** code with `never`: +#### ✅ Correct ```ts async function validNever1() { 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 c275dc5ee05..749b88075bf 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 @@ -23,7 +23,11 @@ function compare(a, b) { In other words, the types are sorted alphabetically, case-insensitively and treating numbers like a human would, falling back to character code sorting in case of ties. -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts type T1 = B | A; @@ -53,7 +57,7 @@ type T4 = | any; ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts type T1 = A | B; diff --git a/packages/eslint-plugin/docs/rules/strict-boolean-expressions.md b/packages/eslint-plugin/docs/rules/strict-boolean-expressions.md index 1d5b0435fe1..eec449b2a58 100644 --- a/packages/eslint-plugin/docs/rules/strict-boolean-expressions.md +++ b/packages/eslint-plugin/docs/rules/strict-boolean-expressions.md @@ -15,7 +15,11 @@ The following nodes are considered boolean expressions and their type is checked ## Examples -Examples of **incorrect** code for this rule: +Examples of code for this rule: + + + +### ❌ Incorrect ```ts // nullable numbers are considered unsafe by default @@ -47,7 +51,7 @@ while (obj) { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```tsx // Using logical operator short-circuiting is allowed diff --git a/packages/eslint-plugin/docs/rules/switch-exhaustiveness-check.md b/packages/eslint-plugin/docs/rules/switch-exhaustiveness-check.md index b5f3ad11f3c..4f11c66eb42 100644 --- a/packages/eslint-plugin/docs/rules/switch-exhaustiveness-check.md +++ b/packages/eslint-plugin/docs/rules/switch-exhaustiveness-check.md @@ -2,7 +2,13 @@ Union type may have a lot of parts. It's easy to forget to consider all cases in switch. This rule reminds which parts are missing. If domain of the problem requires to have only a partial switch, developer may _explicitly_ add a default clause. -Examples of **incorrect** code for this rule: +## Rule Details + +Examples of code for this rule: + + + +### ❌ Incorrect ```ts type Day = @@ -25,7 +31,7 @@ switch (day) { } ``` -Examples of **correct** code for this rule: +### ✅ Correct ```ts type Day = @@ -72,7 +78,7 @@ switch (day) { } ``` -or +### ✅ Correct ```ts type Day = diff --git a/packages/eslint-plugin/docs/rules/type-annotation-spacing.md b/packages/eslint-plugin/docs/rules/type-annotation-spacing.md index cb6b694a15b..f27f7df09c3 100644 --- a/packages/eslint-plugin/docs/rules/type-annotation-spacing.md +++ b/packages/eslint-plugin/docs/rules/type-annotation-spacing.md @@ -45,7 +45,11 @@ This rule has an object option: ### defaults -Examples of **incorrect** code for this rule with no options at all: +Examples of code for this rule with no options at all: + + + +#### ❌ Incorrect ```ts @@ -74,7 +78,7 @@ type Foo = () =>{}; type Foo = ()=> {}; ``` -Examples of **correct** code for this rule with no options at all: +#### ✅ Correct ```ts @@ -91,7 +95,11 @@ type Foo = () => {}; ### after -Examples of **incorrect** code for this rule with `{ "before": false, "after": true }`: +Examples of code for this rule with `{ "before": false, "after": true }`: + + + +#### ❌ Incorrect ```ts @@ -120,7 +128,7 @@ type Foo = () =>{}; type Foo = () => {}; ``` -Examples of **correct** code for this rule with `{ "before": false, "after": true }`: +#### ✅ Correct ```ts @@ -137,7 +145,11 @@ type Foo = ()=> {}; ### before -Examples of **incorrect** code for this rule with `{ "before": true, "after": true }` options: +Examples of code for this rule with `{ "before": true, "after": true }` options: + + + +#### ❌ Incorrect ```ts @@ -166,7 +178,7 @@ type Foo = () =>{}; type Foo = ()=> {}; ``` -Examples of **correct** code for this rule with `{ "before": true, "after": true }` options: +#### ✅ Correct ```ts @@ -183,7 +195,11 @@ type Foo = () => {}; ### overrides - colon -Examples of **incorrect** code for this rule with `{ "before": false, "after": false, overrides: { colon: { before: true, after: true }} }` options: +Examples of code for this rule with `{ "before": false, "after": false, overrides: { colon: { before: true, after: true }} }` options: + + + +#### ❌ Incorrect ```ts @@ -212,7 +228,7 @@ type Foo = ()=> {}; type Foo = () => {}; ``` -Examples of **correct** code for this rule with `{ "before": false, "after": false, overrides: { colon: { before: true, after: true }} }` options: +#### ✅ Correct ```ts @@ -233,7 +249,11 @@ type Foo = ()=>{}; ### overrides - arrow -Examples of **incorrect** code for this rule with `{ "before": false, "after": false, overrides: { arrow: { before: true, after: true }} }` options: +Examples of code for this rule with `{ "before": false, "after": false, overrides: { arrow: { before: true, after: true }} }` options: + + + +#### ❌ Incorrect ```ts @@ -262,7 +282,7 @@ type Foo = () =>{}; type Foo = ()=> {}; ``` -Examples of **correct** code for this rule with `{ "before": false, "after": false, overrides: { arrow: { before: true, after: true }} }` options: +#### ✅ Correct ```ts diff --git a/packages/eslint-plugin/docs/rules/typedef.md b/packages/eslint-plugin/docs/rules/typedef.md index e3de5baf5e5..1351549b737 100644 --- a/packages/eslint-plugin/docs/rules/typedef.md +++ b/packages/eslint-plugin/docs/rules/typedef.md @@ -77,14 +77,18 @@ For example, with the following configuration: Whether to enforce type annotations on variables declared using array destructuring. -Examples of **incorrect** code with `{ "arrayDestructuring": true }`: +Examples of code with `{ "arrayDestructuring": true }`: + + + +#### ❌ Incorrect ```ts const [a] = [1]; const [b, c] = [1, 2]; ``` -Examples of **correct** code with `{ "arrayDestructuring": true }`: +#### ❌ Correct ```ts const [a]: number[] = [1]; @@ -99,7 +103,11 @@ for (const [key, val] of new Map([['key', 1]])) { Whether to enforce type annotations for parameters of arrow functions. -Examples of **incorrect** code with `{ "arrowParameter": true }`: +Examples of code with `{ "arrowParameter": true }`: + + + +#### ❌ Incorrect ```ts const logsSize = size => console.log(size); @@ -111,7 +119,7 @@ const mapper = { }; ``` -Examples of **correct** code with `{ "arrowParameter": true }`: +#### ❌ Correct ```ts const logsSize = (size: number) => console.log(size); @@ -127,7 +135,11 @@ const mapper = { Whether to enforce type annotations on member variables of classes. -Examples of **incorrect** code with `{ "memberVariableDeclaration": true }`: +Examples of code with `{ "memberVariableDeclaration": true }`: + + + +#### ❌ Incorrect ```ts class ContainsText { @@ -136,7 +148,7 @@ class ContainsText { } ``` -Examples of **correct** code with `{ "memberVariableDeclaration": true }`: +#### ❌ Correct ```ts class ContainsText { @@ -149,14 +161,18 @@ class ContainsText { Whether to enforce type annotations on variables declared using object destructuring. -Examples of **incorrect** code with `{ "objectDestructuring": true }`: +Examples of code with `{ "objectDestructuring": true }`: + + + +#### ❌ Incorrect ```ts const { length } = 'text'; const [b, c] = Math.random() ? [1, 2] : [3, 4]; ``` -Examples of **correct** code with `{ "objectDestructuring": true }`: +#### ❌ Correct ```ts const { length }: { length: number } = 'text'; @@ -170,7 +186,11 @@ for (const { key, val } of [{ key: 'key', val: 1 }]) { Whether to enforce type annotations for parameters of functions and methods. -Examples of **incorrect** code with `{ "parameter": true }`: +Examples of code with `{ "parameter": true }`: + + + +#### ❌ Incorrect ```ts function logsSize(size): void { @@ -198,7 +218,7 @@ class Logger { } ``` -Examples of **correct** code with `{ "parameter": true }`: +#### ❌ Correct ```ts function logsSize(size: number): void { @@ -230,7 +250,11 @@ class Logger { Whether to enforce type annotations for properties of interfaces and types. -Examples of **incorrect** code with `{ "propertyDeclaration": true }`: +Examples of code with `{ "propertyDeclaration": true }`: + + + +#### ❌ Incorrect ```ts type Members = { @@ -239,7 +263,7 @@ type Members = { }; ``` -Examples of **correct** code with `{ "propertyDeclaration": true }`: +#### ❌ Correct ```ts type Members = { @@ -252,7 +276,11 @@ type Members = { Whether to enforce type annotations for variable declarations, excluding array and object destructuring. -Examples of **incorrect** code with `{ "variableDeclaration": true }`: +Examples of code with `{ "variableDeclaration": true }`: + + + +#### ❌ Incorrect ```ts const text = 'text'; @@ -260,7 +288,7 @@ let initialText = 'text'; let delayedText; ``` -Examples of **correct** code with `{ "variableDeclaration": true }`: +#### ❌ Correct ```ts const text: string = 'text'; @@ -272,13 +300,17 @@ let delayedText: string; Ignore variable declarations for non-arrow and arrow functions. -Examples of **incorrect** code with `{ "variableDeclaration": true, "variableDeclarationIgnoreFunction": true }`: +Examples of code with `{ "variableDeclaration": true, "variableDeclarationIgnoreFunction": true }`: + + + +#### ❌ Incorrect ```ts const text = 'text'; ``` -Examples of **correct** code with `{ "variableDeclaration": true, "variableDeclarationIgnoreFunction": true }`: +#### ❌ Correct ```ts const a = (): void => {}; diff --git a/packages/eslint-plugin/docs/rules/unbound-method.md b/packages/eslint-plugin/docs/rules/unbound-method.md index 22a9a9039b3..aa9a8c40d09 100644 --- a/packages/eslint-plugin/docs/rules/unbound-method.md +++ b/packages/eslint-plugin/docs/rules/unbound-method.md @@ -10,7 +10,11 @@ If you're working with `jest`, you can use [`eslint-plugin-jest`'s version of th ## Rule Details -Examples of **incorrect** code for this rule +Examples of code for this rule + + + +### ❌ Incorrect ```ts class MyClass { @@ -37,7 +41,7 @@ const arith = { const { double } = arith; ``` -Examples of **correct** code for this rule +### ✅ Correct ```ts class MyClass { diff --git a/packages/website/docusaurus.config.js b/packages/website/docusaurus.config.js index f4db83ff0d7..127228df8b6 100644 --- a/packages/website/docusaurus.config.js +++ b/packages/website/docusaurus.config.js @@ -8,6 +8,8 @@ const remarkPlugins = [ [require('@docusaurus/remark-plugin-npm2yarn'), { sync: true }], ]; +const beforeDefaultRemarkPlugins = [[require('./src/remark/tabs'), {}]]; + const githubUrl = 'https://github.com/typescript-eslint/typescript-eslint'; /** @type {import('@docusaurus/types').Config} */ @@ -30,7 +32,13 @@ const config = { customCss: require.resolve('./src/css/custom.css'), }, ], - ['@docusaurus/plugin-content-pages', { remarkPlugins }], + [ + '@docusaurus/plugin-content-pages', + { + beforeDefaultRemarkPlugins, + remarkPlugins, + }, + ], [ '@docusaurus/plugin-content-docs', { @@ -39,6 +47,7 @@ const config = { sidebarPath: require.resolve('./sidebars/sidebar.rules.js'), routeBasePath: 'rules', editUrl: `${githubUrl}/edit/master/packages/website/`, + beforeDefaultRemarkPlugins, remarkPlugins, }, ], @@ -50,6 +59,7 @@ const config = { routeBasePath: 'docs', sidebarPath: require.resolve('./sidebars/sidebar.base.js'), editUrl: `${githubUrl}/edit/master/packages/website/`, + beforeDefaultRemarkPlugins, remarkPlugins, }, ], diff --git a/packages/website/src/remark/tabs.js b/packages/website/src/remark/tabs.js new file mode 100644 index 00000000000..749dc86ac69 --- /dev/null +++ b/packages/website/src/remark/tabs.js @@ -0,0 +1,120 @@ +const toString = require('mdast-util-to-string'); +const Slugger = require('github-slugger'); +const visit = require('unist-util-visit'); + +const slugs = new Slugger(); + +function renderTabs(tabs, nodes) { + let tabNodes = []; + + tabNodes.push({ + type: 'jsx', + value: ``, + }); + + tabs.forEach(tab => { + const node = nodes[tab.start]; + const label = toString(node); + const id = slugs.slug(label); + + tabNodes.push({ + type: 'jsx', + value: ``, + }); + + tabNodes.push(...nodes.slice(tab.start + 1, tab.end)); + + tabNodes.push({ + type: 'jsx', + value: ``, + }); + }); + + tabNodes.push({ + type: 'jsx', + value: ``, + }); + + return tabNodes; +} + +function findTabs(node, index, parent) { + const tabs = []; + + let depth = null; + + let tab; + const { children } = parent; + + while (++index < children.length) { + const child = children[index]; + + if (child.type === 'heading') { + if (depth == null) { + depth = child.depth; + } + + if (child.depth < depth) { + tab.end = index; + break; + } + + if (child.depth === depth) { + if (tab) { + tab.end = index; + } + + tab = {}; + tab.start = index; + tab.end = children.length; + tabs.push(tab); + } + } + + if (child.type === 'comment' && child.value.trim() === '/tabs') { + tab.end = index; + break; + } + } + + return tabs; +} + +function validator(node) { + return node.type === 'comment' && node.value.trim() === 'tabs'; +} + +function tabs() { + return root => { + slugs.reset(); + let foundTabs = false; + + visit(root, validator, (node, index, parent) => { + const tabs = findTabs(node, index, parent); + const start = tabs[0].start; + const end = tabs[tabs.length - 1].end; + + if (tabs.length > 0) { + foundTabs = true; + const newChildren = renderTabs(tabs, parent.children); + parent.children.splice(start, end - start, ...newChildren); + + return index + newChildren.length; + } + }); + + if (foundTabs) { + root.children.unshift({ + type: 'import', + value: "import TabItem from '@theme/TabItem';", + }); + + root.children.unshift({ + type: 'import', + value: "import Tabs from '@theme/Tabs';", + }); + } + }; +} + +module.exports = tabs; diff --git a/packages/website/src/remark/tabs.license.md b/packages/website/src/remark/tabs.license.md new file mode 100644 index 00000000000..4cba2f24d2d --- /dev/null +++ b/packages/website/src/remark/tabs.license.md @@ -0,0 +1,23 @@ +original code https://github.com/mccleanp/remark-docusaurus-tabs + +MIT License + +Copyright (c) 2020 Paul McClean + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.