Update checked-in dependencies
This commit is contained in:
parent
55ff016766
commit
313daefcef
1570 changed files with 4230 additions and 228668 deletions
1
node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts
generated
vendored
1
node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts
generated
vendored
|
|
@ -147,7 +147,6 @@ declare const _default: {
|
|||
'@typescript-eslint/strict-boolean-expressions': "error";
|
||||
'@typescript-eslint/switch-exhaustiveness-check': "error";
|
||||
'@typescript-eslint/triple-slash-reference': "error";
|
||||
'@typescript-eslint/typedef': "error";
|
||||
'@typescript-eslint/unbound-method': "error";
|
||||
'@typescript-eslint/unified-signatures': "error";
|
||||
'@typescript-eslint/use-unknown-in-catch-callback-variable': "error";
|
||||
|
|
|
|||
2
node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts.map
generated
vendored
2
node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.d.ts.map
generated
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"all.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/all.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBA0JiC"}
|
||||
{"version":3,"file":"all.d.ts","sourceRoot":"","sources":["../../../src/configs/eslintrc/all.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,kBAyJiC"}
|
||||
1
node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.js
generated
vendored
1
node_modules/@typescript-eslint/eslint-plugin/dist/configs/eslintrc/all.js
generated
vendored
|
|
@ -154,7 +154,6 @@ module.exports = {
|
|||
'@typescript-eslint/strict-boolean-expressions': 'error',
|
||||
'@typescript-eslint/switch-exhaustiveness-check': 'error',
|
||||
'@typescript-eslint/triple-slash-reference': 'error',
|
||||
'@typescript-eslint/typedef': 'error',
|
||||
'@typescript-eslint/unbound-method': 'error',
|
||||
'@typescript-eslint/unified-signatures': 'error',
|
||||
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'error',
|
||||
|
|
|
|||
2
node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts.map
generated
vendored
2
node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.d.ts.map
generated
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"all.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/all.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAkKE"}
|
||||
{"version":3,"file":"all.d.ts","sourceRoot":"","sources":["../../../src/configs/flat/all.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAKrE;;;GAGG;yBAED,QAAQ,UAAU,CAAC,MAAM,EACzB,QAAQ,UAAU,CAAC,MAAM,KACxB,UAAU,CAAC,WAAW;AAHzB,wBAiKE"}
|
||||
1
node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.js
generated
vendored
1
node_modules/@typescript-eslint/eslint-plugin/dist/configs/flat/all.js
generated
vendored
|
|
@ -167,7 +167,6 @@ exports.default = (plugin, parser) => [
|
|||
'@typescript-eslint/strict-boolean-expressions': 'error',
|
||||
'@typescript-eslint/switch-exhaustiveness-check': 'error',
|
||||
'@typescript-eslint/triple-slash-reference': 'error',
|
||||
'@typescript-eslint/typedef': 'error',
|
||||
'@typescript-eslint/unbound-method': 'error',
|
||||
'@typescript-eslint/unified-signatures': 'error',
|
||||
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'error',
|
||||
|
|
|
|||
1
node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts
generated
vendored
1
node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts
generated
vendored
|
|
@ -149,7 +149,6 @@ declare const _default: {
|
|||
'@typescript-eslint/strict-boolean-expressions': "error";
|
||||
'@typescript-eslint/switch-exhaustiveness-check': "error";
|
||||
'@typescript-eslint/triple-slash-reference': "error";
|
||||
'@typescript-eslint/typedef': "error";
|
||||
'@typescript-eslint/unbound-method': "error";
|
||||
'@typescript-eslint/unified-signatures': "error";
|
||||
'@typescript-eslint/use-unknown-in-catch-callback-variable': "error";
|
||||
|
|
|
|||
2
node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts.map
generated
vendored
2
node_modules/@typescript-eslint/eslint-plugin/dist/index.d.ts.map
generated
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,kBAA0B"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,kBAA0B"}
|
||||
1
node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts
generated
vendored
1
node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts
generated
vendored
|
|
@ -171,7 +171,6 @@ declare const _default: {
|
|||
'@typescript-eslint/strict-boolean-expressions': "error";
|
||||
'@typescript-eslint/switch-exhaustiveness-check': "error";
|
||||
'@typescript-eslint/triple-slash-reference': "error";
|
||||
'@typescript-eslint/typedef': "error";
|
||||
'@typescript-eslint/unbound-method': "error";
|
||||
'@typescript-eslint/unified-signatures': "error";
|
||||
'@typescript-eslint/use-unknown-in-catch-callback-variable': "error";
|
||||
|
|
|
|||
2
node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts.map
generated
vendored
2
node_modules/@typescript-eslint/eslint-plugin/dist/raw-plugin.d.ts.map
generated
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"raw-plugin.d.ts","sourceRoot":"","sources":["../src/raw-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAU,MAAM,oCAAoC,CAAC;;;;;;;;;;;;;;;;;;wDAetD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAqCpB,mEAAmE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDvE,kBAIE"}
|
||||
{"version":3,"file":"raw-plugin.d.ts","sourceRoot":"","sources":["../src/raw-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAU,MAAM,oCAAoC,CAAC;;;;;;;;;;;;;;;;;;wDAetD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAqCpB,mEAAmE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDvE,kBAIE"}
|
||||
4
node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts
generated
vendored
4
node_modules/@typescript-eslint/eslint-plugin/dist/rules/prefer-destructuring.d.ts
generated
vendored
|
|
@ -1,9 +1,9 @@
|
|||
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
||||
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
|
||||
declare const baseRule: TSESLint.RuleModule<"preferDestructuring", [{
|
||||
declare const baseRule: TSESLint.RuleModule<"preferDestructuring", [import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig | {
|
||||
AssignmentExpression?: import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig;
|
||||
VariableDeclarator?: import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig;
|
||||
} | import("eslint/lib/rules/prefer-destructuring").DestructuringTypeConfig, (import("eslint/lib/rules/prefer-destructuring").Option1 | undefined)?], unknown, {
|
||||
}, (import("eslint/lib/rules/prefer-destructuring").Option1 | undefined)?], unknown, {
|
||||
AssignmentExpression(node: TSESTree.AssignmentExpression): void;
|
||||
VariableDeclarator(node: TSESTree.VariableDeclarator): void;
|
||||
}>;
|
||||
|
|
|
|||
|
|
@ -6,12 +6,12 @@ export type Options = [
|
|||
ignoreConditionalTests?: boolean;
|
||||
ignoreIfStatements?: boolean;
|
||||
ignoreMixedLogicalExpressions?: boolean;
|
||||
ignorePrimitives?: {
|
||||
ignorePrimitives?: true | {
|
||||
bigint?: boolean;
|
||||
boolean?: boolean;
|
||||
number?: boolean;
|
||||
string?: boolean;
|
||||
} | true;
|
||||
};
|
||||
ignoreTernaryTests?: boolean;
|
||||
}
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"prefer-nullish-coalescing.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-nullish-coalescing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAyCnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,sDAAsD,CAAC,EAAE,OAAO,CAAC;QACjE,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,sBAAsB,CAAC,EAAE,OAAO,CAAC;QACjC,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,6BAA6B,CAAC,EAAE,OAAO,CAAC;QACxC,gBAAgB,CAAC,EACb;YACE,MAAM,CAAC,EAAE,OAAO,CAAC;YACjB,OAAO,CAAC,EAAE,OAAO,CAAC;YAClB,MAAM,CAAC,EAAE,OAAO,CAAC;YACjB,MAAM,CAAC,EAAE,OAAO,CAAC;SAClB,GACD,IAAI,CAAC;QACT,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAClB,mBAAmB,GACnB,6BAA6B,GAC7B,qBAAqB,GACrB,0BAA0B,GAC1B,gBAAgB,CAAC;;AAErB,wBA+kBG"}
|
||||
{"version":3,"file":"prefer-nullish-coalescing.d.ts","sourceRoot":"","sources":["../../src/rules/prefer-nullish-coalescing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAY,MAAM,0BAA0B,CAAC;AAyCnE,MAAM,MAAM,OAAO,GAAG;IACpB;QACE,sDAAsD,CAAC,EAAE,OAAO,CAAC;QACjE,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,sBAAsB,CAAC,EAAE,OAAO,CAAC;QACjC,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,6BAA6B,CAAC,EAAE,OAAO,CAAC;QACxC,gBAAgB,CAAC,EACb,IAAI,GACJ;YACE,MAAM,CAAC,EAAE,OAAO,CAAC;YACjB,OAAO,CAAC,EAAE,OAAO,CAAC;YAClB,MAAM,CAAC,EAAE,OAAO,CAAC;YACjB,MAAM,CAAC,EAAE,OAAO,CAAC;SAClB,CAAC;QACN,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;CACF,CAAC;AAEF,MAAM,MAAM,UAAU,GAClB,mBAAmB,GACnB,6BAA6B,GAC7B,qBAAqB,GACrB,0BAA0B,GAC1B,gBAAgB,CAAC;;AAErB,wBA+kBG"}
|
||||
2
node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts.map
generated
vendored
2
node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.d.ts.map
generated
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"typedef.d.ts","sourceRoot":"","sources":["../../src/rules/typedef.ts"],"names":[],"mappings":"AAMA,0BAAkB,UAAU;IAC1B,kBAAkB,uBAAuB;IACzC,cAAc,mBAAmB;IACjC,yBAAyB,8BAA8B;IACvD,mBAAmB,wBAAwB;IAC3C,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,mBAAmB,wBAAwB;IAC3C,iCAAiC,sCAAsC;CACxE;AAED,MAAM,MAAM,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7D,MAAM,MAAM,UAAU,GAAG,iBAAiB,GAAG,sBAAsB,CAAC;;AAEpE,wBAiSG"}
|
||||
{"version":3,"file":"typedef.d.ts","sourceRoot":"","sources":["../../src/rules/typedef.ts"],"names":[],"mappings":"AAMA,0BAAkB,UAAU;IAC1B,kBAAkB,uBAAuB;IACzC,cAAc,mBAAmB;IACjC,yBAAyB,8BAA8B;IACvD,mBAAmB,wBAAwB;IAC3C,SAAS,cAAc;IACvB,mBAAmB,wBAAwB;IAC3C,mBAAmB,wBAAwB;IAC3C,iCAAiC,sCAAsC;CACxE;AAED,MAAM,MAAM,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AAE7D,MAAM,MAAM,UAAU,GAAG,iBAAiB,GAAG,sBAAsB,CAAC;;AAEpE,wBAqSG"}
|
||||
4
node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.js
generated
vendored
4
node_modules/@typescript-eslint/eslint-plugin/dist/rules/typedef.js
generated
vendored
|
|
@ -18,6 +18,10 @@ exports.default = (0, util_1.createRule)({
|
|||
name: 'typedef',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
deprecated: {
|
||||
deprecatedSince: '8.33.0',
|
||||
message: 'This is an old rule that is no longer recommended for use.',
|
||||
},
|
||||
docs: {
|
||||
description: 'Require type annotations in certain places',
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"collectUnusedVariables.d.ts","sourceRoot":"","sources":["../../src/util/collectUnusedVariables.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EACd,MAAM,kCAAkC,CAAC;AAQ1C,OAAO,EAIL,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAKlC,UAAU,gBAAgB;IACxB,QAAQ,CAAC,eAAe,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;IACrD,QAAQ,CAAC,aAAa,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;CACpD;AAqxBD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,GAC3D,gBAAgB,CAQlB"}
|
||||
{"version":3,"file":"collectUnusedVariables.d.ts","sourceRoot":"","sources":["../../src/util/collectUnusedVariables.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EACd,MAAM,kCAAkC,CAAC;AAQ1C,OAAO,EAIL,QAAQ,EACT,MAAM,0BAA0B,CAAC;AAKlC,UAAU,gBAAgB;IACxB,QAAQ,CAAC,eAAe,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;IACrD,QAAQ,CAAC,aAAa,EAAE,WAAW,CAAC,aAAa,CAAC,CAAC;CACpD;AAmxBD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,SAAS,OAAO,EAAE,EAElC,OAAO,EAAE,QAAQ,CAAC,QAAQ,CAAC,WAAW,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,GAC3D,gBAAgB,CAQlB"}
|
||||
57
node_modules/@typescript-eslint/eslint-plugin/docs/rules/README.md
generated
vendored
57
node_modules/@typescript-eslint/eslint-plugin/docs/rules/README.md
generated
vendored
|
|
@ -1,57 +0,0 @@
|
|||
---
|
||||
title: Overview
|
||||
sidebar_label: Overview
|
||||
pagination_next: null
|
||||
pagination_prev: null
|
||||
slug: /
|
||||
---
|
||||
|
||||
`@typescript-eslint/eslint-plugin` includes over 100 rules that detect best practice violations, bugs, and/or stylistic issues specifically for TypeScript code. All of our rules are listed below.
|
||||
|
||||
:::tip
|
||||
Instead of enabling rules one by one, we recommend using one of [our pre-defined configs](/users/configs) to enable a large set of recommended rules.
|
||||
:::
|
||||
|
||||
## Rules
|
||||
|
||||
The rules are listed in alphabetical order. You can optionally filter them based on these categories:
|
||||
|
||||
import RulesTable from "@site/src/components/RulesTable";
|
||||
|
||||
<RulesTable />
|
||||
|
||||
## Filtering
|
||||
|
||||
### Config Group (⚙️)
|
||||
|
||||
"Config Group" refers to the [pre-defined config](/users/configs) that includes the rule. Extending from a configuration preset allow for enabling a large set of recommended rules all at once.
|
||||
|
||||
### Metadata
|
||||
|
||||
- `🔧 fixable` refers to whether the rule contains an [ESLint `--fix` auto-fixer](https://eslint.org/docs/latest/use/command-line-interface#--fix).
|
||||
- `💡 has suggestions` refers to whether the rule contains an ESLint suggestion fixer.
|
||||
- Sometimes, it is not safe to automatically fix the code with an auto-fixer. But in these cases, we often have a good guess of what the correct fix should be, and we can provide it as a suggestion to the developer.
|
||||
- `💭 requires type information` refers to whether the rule requires [typed linting](/getting-started/typed-linting).
|
||||
- `🧱 extension rule` means that the rule is an extension of an [core ESLint rule](https://eslint.org/docs/latest/rules) (see [Extension Rules](#extension-rules)).
|
||||
- `💀 deprecated rule` means that the rule should no longer be used and will be removed from the plugin in a future version.
|
||||
|
||||
## Extension Rules
|
||||
|
||||
Some core ESLint rules do not support TypeScript syntax: either they crash, ignore the syntax, or falsely report against it.
|
||||
In these cases, we create what we call an "extension rule": a rule within our plugin that has the same functionality, but also supports TypeScript.
|
||||
|
||||
Extension rules generally completely replace the base rule from ESLint core.
|
||||
If the base rule is enabled in a config you extend from, you'll need to disable the base rule:
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
extends: ['eslint:recommended'],
|
||||
rules: {
|
||||
// Note: you must disable the base rule as it can report incorrect errors
|
||||
'no-unused-vars': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'error',
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
[Search for `🧱 extension rule`s](?=extension#rules) in this page to see all extension rules.
|
||||
36
node_modules/@typescript-eslint/eslint-plugin/docs/rules/TEMPLATE.md
generated
vendored
36
node_modules/@typescript-eslint/eslint-plugin/docs/rules/TEMPLATE.md
generated
vendored
|
|
@ -1,36 +0,0 @@
|
|||
---
|
||||
description: '<Description from rule metadata here>'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/RULE_NAME_REPLACEME** for documentation.
|
||||
|
||||
## Examples
|
||||
|
||||
To fill out: tell us more about this rule.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// To fill out: incorrect code
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// To fill out: correct code
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
To fill out: why wouldn't you want to use this rule?
|
||||
For example if this rule requires a feature released in a certain TS version.
|
||||
105
node_modules/@typescript-eslint/eslint-plugin/docs/rules/adjacent-overload-signatures.mdx
generated
vendored
105
node_modules/@typescript-eslint/eslint-plugin/docs/rules/adjacent-overload-signatures.mdx
generated
vendored
|
|
@ -1,105 +0,0 @@
|
|||
---
|
||||
description: 'Require that function overload signatures be consecutive.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/adjacent-overload-signatures** for documentation.
|
||||
|
||||
Function overload signatures represent multiple ways a function can be called, potentially with different return types.
|
||||
It's typical for an interface or type alias describing a function to place all overload signatures next to each other.
|
||||
If Signatures placed elsewhere in the type are easier to be missed by future developers reading the code.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
declare namespace Foo {
|
||||
export function foo(s: string): void;
|
||||
export function foo(n: number): void;
|
||||
export function bar(): void;
|
||||
export function foo(sn: string | number): void;
|
||||
}
|
||||
|
||||
type Foo = {
|
||||
foo(s: string): void;
|
||||
foo(n: number): void;
|
||||
bar(): void;
|
||||
foo(sn: string | number): void;
|
||||
};
|
||||
|
||||
interface Foo {
|
||||
foo(s: string): void;
|
||||
foo(n: number): void;
|
||||
bar(): void;
|
||||
foo(sn: string | number): void;
|
||||
}
|
||||
|
||||
class Foo {
|
||||
foo(s: string): void;
|
||||
foo(n: number): void;
|
||||
bar(): void {}
|
||||
foo(sn: string | number): void {}
|
||||
}
|
||||
|
||||
export function foo(s: string): void;
|
||||
export function foo(n: number): void;
|
||||
export function bar(): void;
|
||||
export function foo(sn: string | number): void;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
declare namespace Foo {
|
||||
export function foo(s: string): void;
|
||||
export function foo(n: number): void;
|
||||
export function foo(sn: string | number): void;
|
||||
export function bar(): void;
|
||||
}
|
||||
|
||||
type Foo = {
|
||||
foo(s: string): void;
|
||||
foo(n: number): void;
|
||||
foo(sn: string | number): void;
|
||||
bar(): void;
|
||||
};
|
||||
|
||||
interface Foo {
|
||||
foo(s: string): void;
|
||||
foo(n: number): void;
|
||||
foo(sn: string | number): void;
|
||||
bar(): void;
|
||||
}
|
||||
|
||||
class Foo {
|
||||
foo(s: string): void;
|
||||
foo(n: number): void;
|
||||
foo(sn: string | number): void {}
|
||||
bar(): void {}
|
||||
}
|
||||
|
||||
export function bar(): void;
|
||||
export function foo(s: string): void;
|
||||
export function foo(n: number): void;
|
||||
export function foo(sn: string | number): void;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
It can sometimes be useful to place overload signatures alongside other meaningful parts of a type.
|
||||
For example, if each of a function's overloads corresponds to a different property, you might wish to put each overloads next to its corresponding property.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`unified-signatures`](./unified-signatures.mdx)
|
||||
126
node_modules/@typescript-eslint/eslint-plugin/docs/rules/array-type.mdx
generated
vendored
126
node_modules/@typescript-eslint/eslint-plugin/docs/rules/array-type.mdx
generated
vendored
|
|
@ -1,126 +0,0 @@
|
|||
---
|
||||
description: 'Require consistently using either `T[]` or `Array<T>` for arrays.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/array-type** for documentation.
|
||||
|
||||
TypeScript provides two equivalent ways to define an array type: `T[]` and `Array<T>`.
|
||||
The two styles are functionally equivalent.
|
||||
Using the same style consistently across your codebase makes it easier for developers to read and understand array types.
|
||||
|
||||
## Options
|
||||
|
||||
The default config will enforce that all mutable and readonly arrays use the `'array'` syntax.
|
||||
|
||||
### `"array"`
|
||||
|
||||
Always use `T[]` or `readonly T[]` for all array types.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "default": "array" }'
|
||||
const x: Array<string> = ['a', 'b'];
|
||||
const y: ReadonlyArray<string> = ['a', 'b'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "default": "array" }'
|
||||
const x: string[] = ['a', 'b'];
|
||||
const y: readonly string[] = ['a', 'b'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `"generic"`
|
||||
|
||||
Always use `Array<T>`, `ReadonlyArray<T>`, or `Readonly<Array<T>>` for all array types.
|
||||
`readonly T[]` will be modified to `ReadonlyArray<T>` and `Readonly<T[]>` will be modified to `Readonly<Array<T>>`.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "default": "generic" }'
|
||||
const x: string[] = ['a', 'b'];
|
||||
const y: readonly string[] = ['a', 'b'];
|
||||
const z: Readonly<string[]> = ['a', 'b'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "default": "generic" }'
|
||||
const x: Array<string> = ['a', 'b'];
|
||||
const y: ReadonlyArray<string> = ['a', 'b'];
|
||||
const z: Readonly<Array<string>> = ['a', 'b'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `"array-simple"`
|
||||
|
||||
Use `T[]` or `readonly T[]` for simple types (i.e. types which are just primitive names or type references).
|
||||
Use `Array<T>` or `ReadonlyArray<T>` for all other types (union types, intersection types, object types, function types, etc).
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "default": "array-simple" }'
|
||||
const a: (string | number)[] = ['a', 'b'];
|
||||
const b: { prop: string }[] = [{ prop: 'a' }];
|
||||
const c: (() => void)[] = [() => {}];
|
||||
const d: Array<MyType> = ['a', 'b'];
|
||||
const e: Array<string> = ['a', 'b'];
|
||||
const f: ReadonlyArray<string> = ['a', 'b'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "default": "array-simple" }'
|
||||
const a: Array<string | number> = ['a', 'b'];
|
||||
const b: Array<{ prop: string }> = [{ prop: 'a' }];
|
||||
const c: Array<() => void> = [() => {}];
|
||||
const d: MyType[] = ['a', 'b'];
|
||||
const e: string[] = ['a', 'b'];
|
||||
const f: readonly string[] = ['a', 'b'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Combination Matrix
|
||||
|
||||
This matrix lists all possible option combinations and their expected results for different types of Arrays.
|
||||
|
||||
| defaultOption | readonlyOption | Array with simple type | Array with non simple type | Readonly array with simple type | Readonly array with non simple type |
|
||||
| -------------- | -------------- | ---------------------- | -------------------------- | ------------------------------- | ----------------------------------- |
|
||||
| `array` | | `number[]` | `(Foo & Bar)[]` | `readonly number[]` | `readonly (Foo & Bar)[]` |
|
||||
| `array` | `array` | `number[]` | `(Foo & Bar)[]` | `readonly number[]` | `readonly (Foo & Bar)[]` |
|
||||
| `array` | `array-simple` | `number[]` | `(Foo & Bar)[]` | `readonly number[]` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `array` | `generic` | `number[]` | `(Foo & Bar)[]` | `ReadonlyArray<number>` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `array-simple` | | `number[]` | `Array<Foo & Bar>` | `readonly number[]` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `array-simple` | `array` | `number[]` | `Array<Foo & Bar>` | `readonly number[]` | `readonly (Foo & Bar)[]` |
|
||||
| `array-simple` | `array-simple` | `number[]` | `Array<Foo & Bar>` | `readonly number[]` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `array-simple` | `generic` | `number[]` | `Array<Foo & Bar>` | `ReadonlyArray<number>` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `generic` | | `Array<number>` | `Array<Foo & Bar>` | `ReadonlyArray<number>` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `generic` | `array` | `Array<number>` | `Array<Foo & Bar>` | `readonly number[]` | `readonly (Foo & Bar)[]` |
|
||||
| `generic` | `array-simple` | `Array<number>` | `Array<Foo & Bar>` | `readonly number[]` | `ReadonlyArray<Foo & Bar>` |
|
||||
| `generic` | `generic` | `Array<number>` | `Array<Foo & Bar>` | `ReadonlyArray<number>` | `ReadonlyArray<Foo & Bar>` |
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
This rule is purely a stylistic rule for maintaining consistency in your project.
|
||||
You can turn it off if you don't want to keep a consistent style for array types.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
184
node_modules/@typescript-eslint/eslint-plugin/docs/rules/await-thenable.mdx
generated
vendored
184
node_modules/@typescript-eslint/eslint-plugin/docs/rules/await-thenable.mdx
generated
vendored
|
|
@ -1,184 +0,0 @@
|
|||
---
|
||||
description: 'Disallow awaiting a value that is not a Thenable.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/await-thenable** for documentation.
|
||||
|
||||
A "Thenable" value is an object which has a `then` method, such as a Promise.
|
||||
The [`await` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) is generally used to retrieve the result of calling a Thenable's `then` method.
|
||||
|
||||
If the `await` keyword is used on a value that is not a Thenable, the value is directly resolved, but will still pause execution until the next microtask.
|
||||
While doing so is valid JavaScript, it is often a programmer error, such as forgetting to add parenthesis to call a function that returns a Promise.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
await 'value';
|
||||
|
||||
const createValue = () => 'value';
|
||||
await createValue();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
await Promise.resolve('value');
|
||||
|
||||
const createValue = async () => 'value';
|
||||
await createValue();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Async Iteration (`for await...of` Loops)
|
||||
|
||||
This rule also inspects [`for await...of` statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of), and reports if the value being iterated over is not async-iterable.
|
||||
|
||||
:::info[Why does the rule report on `for await...of` loops used on an array of Promises?]
|
||||
|
||||
While `for await...of` can be used with synchronous iterables, and it will await each promise produced by the iterable, it is inadvisable to do so.
|
||||
There are some tiny nuances that you may want to consider.
|
||||
|
||||
The biggest difference between using `for await...of` and using `for...of` (apart from awaiting each result yourself) is error handling.
|
||||
When an error occurs within the loop body, `for await...of` does _not_ close the original sync iterable, while `for...of` does.
|
||||
For detailed examples of this, see the [MDN documentation on using `for await...of` with sync-iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of#iterating_over_sync_iterables_and_generators).
|
||||
|
||||
Also consider whether you need sequential awaiting at all. Using `for await...of` may obscure potential opportunities for concurrent processing, such as those reported by [`no-await-in-loop`](https://eslint.org/docs/latest/rules/no-await-in-loop). Consider instead using one of the [promise concurrency methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) for better performance.
|
||||
|
||||
:::
|
||||
|
||||
### Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
async function syncIterable() {
|
||||
const arrayOfValues = [1, 2, 3];
|
||||
for await (const value of arrayOfValues) {
|
||||
console.log(value);
|
||||
}
|
||||
}
|
||||
|
||||
async function syncIterableOfPromises() {
|
||||
const arrayOfPromises = [
|
||||
Promise.resolve(1),
|
||||
Promise.resolve(2),
|
||||
Promise.resolve(3),
|
||||
];
|
||||
for await (const promisedValue of arrayOfPromises) {
|
||||
console.log(promisedValue);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
async function syncIterable() {
|
||||
const arrayOfValues = [1, 2, 3];
|
||||
for (const value of arrayOfValues) {
|
||||
console.log(value);
|
||||
}
|
||||
}
|
||||
|
||||
async function syncIterableOfPromises() {
|
||||
const arrayOfPromises = [
|
||||
Promise.resolve(1),
|
||||
Promise.resolve(2),
|
||||
Promise.resolve(3),
|
||||
];
|
||||
for (const promisedValue of await Promise.all(arrayOfPromises)) {
|
||||
console.log(promisedValue);
|
||||
}
|
||||
}
|
||||
|
||||
async function validUseOfForAwaitOnAsyncIterable() {
|
||||
async function* yieldThingsAsynchronously() {
|
||||
yield 1;
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
yield 2;
|
||||
}
|
||||
|
||||
for await (const promisedValue of yieldThingsAsynchronously()) {
|
||||
console.log(promisedValue);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Explicit Resource Management (`await using` Statements)
|
||||
|
||||
This rule also inspects [`await using` statements](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management).
|
||||
If the disposable being used is not async-disposable, an `await using` statement is unnecessary.
|
||||
|
||||
### Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
function makeSyncDisposable(): Disposable {
|
||||
return {
|
||||
[Symbol.dispose](): void {
|
||||
// Dispose of the resource
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function shouldNotAwait() {
|
||||
await using resource = makeSyncDisposable();
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
function makeSyncDisposable(): Disposable {
|
||||
return {
|
||||
[Symbol.dispose](): void {
|
||||
// Dispose of the resource
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function shouldNotAwait() {
|
||||
using resource = makeSyncDisposable();
|
||||
}
|
||||
|
||||
function makeAsyncDisposable(): AsyncDisposable {
|
||||
return {
|
||||
async [Symbol.asyncDispose](): Promise<void> {
|
||||
// Dispose of the resource asynchronously
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function shouldAwait() {
|
||||
await using resource = makeAsyncDisposable();
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you want to allow code to `await` non-Promise values.
|
||||
For example, if your framework is in transition from one style of asynchronous code to another, it may be useful to include `await`s unnecessarily.
|
||||
This is generally not preferred but can sometimes be useful for visual consistency.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
165
node_modules/@typescript-eslint/eslint-plugin/docs/rules/ban-ts-comment.mdx
generated
vendored
165
node_modules/@typescript-eslint/eslint-plugin/docs/rules/ban-ts-comment.mdx
generated
vendored
|
|
@ -1,165 +0,0 @@
|
|||
---
|
||||
description: 'Disallow `@ts-<directive>` comments or require descriptions after directives.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/ban-ts-comment** for documentation.
|
||||
|
||||
TypeScript provides several directive comments that can be used to alter how it processes files.
|
||||
Using these to suppress TypeScript compiler errors reduces the effectiveness of TypeScript overall.
|
||||
Instead, it's generally better to correct the types of code, to make directives unnecessary.
|
||||
|
||||
The directive comments supported by TypeScript are:
|
||||
|
||||
```ts
|
||||
// @ts-expect-error
|
||||
// @ts-ignore
|
||||
// @ts-nocheck
|
||||
// @ts-check
|
||||
```
|
||||
|
||||
This rule lets you set which directive comments you want to allow in your codebase.
|
||||
|
||||
## Options
|
||||
|
||||
By default, only `@ts-check` is allowed, as it enables rather than suppresses errors.
|
||||
|
||||
### `ts-expect-error`, `ts-ignore`, `ts-nocheck`, `ts-check` directives
|
||||
|
||||
A value of `true` for a particular directive means that this rule will report if it finds any usage of said directive.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "ts-ignore": true }'
|
||||
if (false) {
|
||||
// @ts-ignore: Unreachable code error
|
||||
console.log('hello');
|
||||
}
|
||||
if (false) {
|
||||
/* @ts-ignore: Unreachable code error */
|
||||
console.log('hello');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "ts-ignore": true }'
|
||||
if (false) {
|
||||
// Compiler warns about unreachable code error
|
||||
console.log('hello');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allow-with-description`
|
||||
|
||||
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' }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "ts-expect-error": "allow-with-description" }'
|
||||
if (false) {
|
||||
// @ts-expect-error
|
||||
console.log('hello');
|
||||
}
|
||||
if (false) {
|
||||
/* @ts-expect-error */
|
||||
console.log('hello');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "ts-expect-error": "allow-with-description" }'
|
||||
if (false) {
|
||||
// @ts-expect-error: Unreachable code error
|
||||
console.log('hello');
|
||||
}
|
||||
if (false) {
|
||||
/* @ts-expect-error: Unreachable code error */
|
||||
console.log('hello');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
### `descriptionFormat`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
For each directive type, you can specify a custom format in the form of a regular expression. Only description that matches the pattern will be allowed.
|
||||
|
||||
For example, with `{ 'ts-expect-error': { descriptionFormat: '^: TS\\d+ because .+$' } }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
{/* prettier-ignore */}
|
||||
```ts option='{ "ts-expect-error": { "descriptionFormat": "^: TS\\\\d+ because .+$" } }'
|
||||
// @ts-expect-error: the library definition is wrong
|
||||
const a = doSomething('hello');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
{/* prettier-ignore */}
|
||||
```ts option='{ "ts-expect-error": { "descriptionFormat": "^: TS\\\\d+ because .+$" } }'
|
||||
// @ts-expect-error: TS1234 because the library definition is wrong
|
||||
const a = doSomething('hello');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `minimumDescriptionLength`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
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:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "ts-expect-error": "allow-with-description", "minimumDescriptionLength": 10 }'
|
||||
if (false) {
|
||||
// @ts-expect-error: TODO
|
||||
console.log('hello');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "ts-expect-error": "allow-with-description", "minimumDescriptionLength": 10 }'
|
||||
if (false) {
|
||||
// @ts-expect-error The rationale for this override is described in issue #1337 on GitLab
|
||||
console.log('hello');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project or its dependencies were not architected with strong type safety in mind, it can be difficult to always adhere to proper TypeScript semantics.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- TypeScript [Type Checking JavaScript Files](https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html)
|
||||
45
node_modules/@typescript-eslint/eslint-plugin/docs/rules/ban-tslint-comment.mdx
generated
vendored
45
node_modules/@typescript-eslint/eslint-plugin/docs/rules/ban-tslint-comment.mdx
generated
vendored
|
|
@ -1,45 +0,0 @@
|
|||
---
|
||||
description: 'Disallow `// tslint:<rule-flag>` comments.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/ban-tslint-comment** for documentation.
|
||||
|
||||
Useful when migrating from TSLint to ESLint. Once TSLint has been removed, this rule helps locate TSLint annotations (e.g. `// tslint:disable`).
|
||||
|
||||
> See the [TSLint rule flags docs](https://palantir.github.io/tslint/usage/rule-flags) for reference.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
/* tslint:disable */
|
||||
/* tslint:enable */
|
||||
/* tslint:disable:rule1 rule2 rule3... */
|
||||
/* tslint:enable:rule1 rule2 rule3... */
|
||||
// tslint:disable-next-line
|
||||
someCode(); // tslint:disable-line
|
||||
// tslint:disable-next-line:rule1 rule2 rule3...
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// 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
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you are still using TSLint alongside ESLint.
|
||||
26
node_modules/@typescript-eslint/eslint-plugin/docs/rules/ban-types.md
generated
vendored
26
node_modules/@typescript-eslint/eslint-plugin/docs/rules/ban-types.md
generated
vendored
|
|
@ -1,26 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
The old `ban-types` rule encompassed multiple areas of functionality, and so has been split into several rules.
|
||||
|
||||
**[`no-restricted-types`](./no-restricted-types.mdx)** is the new rule for banning a configurable list of type names.
|
||||
It has no options enabled by default and is akin to rules like [`no-restricted-globals`](https://eslint.org/docs/latest/rules/no-restricted-globals), [`no-restricted-properties`](https://eslint.org/docs/latest/rules/no-restricted-properties), and [`no-restricted-syntax`](https://eslint.org/docs/latest/rules/no-restricted-syntax).
|
||||
|
||||
The default options from `ban-types` are now covered by:
|
||||
|
||||
- **[`no-empty-object-type`](./no-empty-object-type.mdx)**: banning the built-in `{}` type in confusing locations
|
||||
- **[`no-unsafe-function-type`](./no-unsafe-function-type.mdx)**: banning the built-in `Function`
|
||||
- **[`no-wrapper-object-types`](./no-wrapper-object-types.mdx)**: banning `Object` and built-in class wrappers such as `Number`
|
||||
|
||||
`ban-types` itself is removed in typescript-eslint v8.
|
||||
See [Announcing typescript-eslint v8 Beta](/blog/announcing-typescript-eslint-v8-beta) for more details.
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose because `ban-types` is a well-known
|
||||
rule. This exists to help direct people to the replacement rules.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/block-spacing.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/block-spacing.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/brace-style.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/brace-style.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/camelcase.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/camelcase.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been deprecated in favour of the [`naming-convention`](./naming-convention.mdx) rule.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose because `camelcase` is a core ESLint
|
||||
rule. This exists to help direct people to the replacement rule.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
112
node_modules/@typescript-eslint/eslint-plugin/docs/rules/class-literal-property-style.mdx
generated
vendored
112
node_modules/@typescript-eslint/eslint-plugin/docs/rules/class-literal-property-style.mdx
generated
vendored
|
|
@ -1,112 +0,0 @@
|
|||
---
|
||||
description: 'Enforce that literals on classes are exposed in a consistent style.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/class-literal-property-style** for documentation.
|
||||
|
||||
Some TypeScript applications store literal values on classes using fields with the `readonly` modifier to prevent them from being reassigned.
|
||||
When writing TypeScript libraries that could be used by JavaScript users, however, it's typically safer to expose these literals using `getter`s, since the `readonly` modifier is enforced at compile type.
|
||||
|
||||
This rule aims to ensure that literals exposed by classes are done so consistently, in one of the two style described above.
|
||||
By default this rule prefers the `fields` style as it means JS doesn't have to setup & teardown a function closure.
|
||||
|
||||
## Options
|
||||
|
||||
:::note
|
||||
This rule only checks for constant _literal_ values (string, template string, number, bigint, boolean, regexp, null). It does not check objects or arrays, because a readonly field behaves differently to a getter in those cases. It also does not check functions, as it is a common pattern to use readonly fields with arrow function values as auto-bound methods.
|
||||
This is because these types can be mutated and carry with them more complex implications about their usage.
|
||||
:::
|
||||
|
||||
### `"fields"`
|
||||
|
||||
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 code with the `fields` style:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"fields"'
|
||||
class Mx {
|
||||
public static get myField1() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
private get ['myField2']() {
|
||||
return 'hello world';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"fields"'
|
||||
class Mx {
|
||||
public readonly myField1 = 1;
|
||||
|
||||
// not a literal
|
||||
public readonly myField2 = [1, 2, 3];
|
||||
|
||||
private readonly ['myField3'] = 'hello world';
|
||||
|
||||
public get myField4() {
|
||||
return `hello from ${window.location.href}`;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `"getters"`
|
||||
|
||||
This style checks for any `readonly` fields that are assigned literal values, and requires them to be defined as getters instead.
|
||||
This style pairs well with the [`@typescript-eslint/prefer-readonly`](prefer-readonly.mdx) rule,
|
||||
as it will identify fields that can be `readonly`, and thus should be made into getters.
|
||||
|
||||
Examples of code with the `getters` style:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"getters"'
|
||||
class Mx {
|
||||
readonly myField1 = 1;
|
||||
readonly myField2 = `hello world`;
|
||||
private readonly myField3 = 'hello world';
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"getters"'
|
||||
class Mx {
|
||||
// no readonly modifier
|
||||
public myField1 = 'hello';
|
||||
|
||||
// not a literal
|
||||
public readonly myField2 = [1, 2, 3];
|
||||
|
||||
public static get myField3() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
private get ['myField4']() {
|
||||
return 'hello world';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
When you have no strong preference, or do not wish to enforce a particular style for how literal values are exposed by your classes.
|
||||
135
node_modules/@typescript-eslint/eslint-plugin/docs/rules/class-methods-use-this.mdx
generated
vendored
135
node_modules/@typescript-eslint/eslint-plugin/docs/rules/class-methods-use-this.mdx
generated
vendored
|
|
@ -1,135 +0,0 @@
|
|||
---
|
||||
description: 'Enforce that class methods utilize `this`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/class-methods-use-this** for documentation.
|
||||
|
||||
It adds support for ignoring `override` methods and/or methods on classes that implement an interface. It also supports auto-accessor properties.
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
interface Options extends BaseClassMethodsUseThisOptions {
|
||||
ignoreOverrideMethods?: boolean;
|
||||
ignoreClassesThatImplementAnInterface?: boolean | 'public-fields';
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
...baseClassMethodsUseThisOptions,
|
||||
ignoreOverrideMethods: false,
|
||||
ignoreClassesThatImplementAnInterface: false,
|
||||
};
|
||||
```
|
||||
|
||||
### `ignoreOverrideMethods`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Example of correct code when `ignoreOverrideMethods` is set to `true`:
|
||||
|
||||
```ts option='{ "ignoreOverrideMethods": true }' showPlaygroundButton
|
||||
abstract class Base {
|
||||
abstract method(): void;
|
||||
abstract property: () => void;
|
||||
}
|
||||
|
||||
class Derived extends Base {
|
||||
override method() {}
|
||||
override property = () => {};
|
||||
}
|
||||
```
|
||||
|
||||
### `ignoreClassesThatImplementAnInterface`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
If specified, it can be either:
|
||||
|
||||
- `true`: Ignore all classes that implement an interface
|
||||
- `'public-fields'`: Ignore only the public fields of classes that implement an interface
|
||||
|
||||
Note that this option applies to all class members, not just those defined in the interface.
|
||||
|
||||
#### `true`
|
||||
|
||||
Examples of code when `ignoreClassesThatImplementAnInterface` is set to `true`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "ignoreClassesThatImplementAnInterface": true }' showPlaygroundButton
|
||||
class Standalone {
|
||||
method() {}
|
||||
property = () => {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "ignoreClassesThatImplementAnInterface": true }' showPlaygroundButton
|
||||
interface Base {
|
||||
method(): void;
|
||||
}
|
||||
|
||||
class Derived implements Base {
|
||||
method() {}
|
||||
property = () => {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
#### `'public-fields'`
|
||||
|
||||
Example of incorrect code when `ignoreClassesThatImplementAnInterface` is set to `'public-fields'`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "ignoreClassesThatImplementAnInterface": "public-fields" }' showPlaygroundButton
|
||||
interface Base {
|
||||
method(): void;
|
||||
}
|
||||
|
||||
class Derived implements Base {
|
||||
method() {}
|
||||
property = () => {};
|
||||
|
||||
private privateMethod() {}
|
||||
private privateProperty = () => {};
|
||||
|
||||
protected protectedMethod() {}
|
||||
protected protectedProperty = () => {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "ignoreClassesThatImplementAnInterface": "public-fields" }'
|
||||
interface Base {
|
||||
method(): void;
|
||||
}
|
||||
|
||||
class Derived implements Base {
|
||||
method() {}
|
||||
property = () => {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project dynamically changes `this` scopes around in a way TypeScript has difficulties modeling, this rule may not be viable to use.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/comma-dangle.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/comma-dangle.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/comma-spacing.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/comma-spacing.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
---
|
||||
description: 'Enforce specifying generic type arguments on type annotation or constructor name of a constructor call.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-generic-constructors** for documentation.
|
||||
|
||||
When constructing a generic class, you can specify the type arguments on either the left-hand side (as a type annotation) or the right-hand side (as part of the constructor call):
|
||||
|
||||
```ts
|
||||
// Left-hand side
|
||||
const map: Map<string, number> = new Map();
|
||||
|
||||
// Right-hand side
|
||||
const map = new Map<string, number>();
|
||||
```
|
||||
|
||||
This rule ensures that type arguments appear consistently on one side of the declaration.
|
||||
Keeping to one side consistently improve code readability.
|
||||
|
||||
> The rule never reports when there are type parameters on both sides, or neither sides of the declaration.
|
||||
> It also doesn't report if the names of the type annotation and the constructor don't match.
|
||||
|
||||
## Options
|
||||
|
||||
- `'constructor'` _(default)_: type arguments that **only** appear on the type annotation are disallowed.
|
||||
- `'type-annotation'`: type arguments that **only** appear on the constructor are disallowed.
|
||||
|
||||
### `'constructor'`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"constructor"'
|
||||
const map: Map<string, number> = new Map();
|
||||
const set: Set<string> = new Set();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"constructor"'
|
||||
const map = new Map<string, number>();
|
||||
const map: Map<string, number> = new MyMap();
|
||||
const set = new Set<string>();
|
||||
const set = new Set();
|
||||
const set: Set<string> = new Set<string>();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `'type-annotation'`
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"type-annotation"'
|
||||
const map = new Map<string, number>();
|
||||
const set = new Set<string>();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"type-annotation"'
|
||||
const map: Map<string, number> = new Map();
|
||||
const set: Set<string> = new Set();
|
||||
const set = new Set();
|
||||
const set: Set<string> = new Set<string>();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
You can turn this rule off if you don't want to enforce one kind of generic constructor style over the other.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
105
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-indexed-object-style.mdx
generated
vendored
105
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-indexed-object-style.mdx
generated
vendored
|
|
@ -1,105 +0,0 @@
|
|||
---
|
||||
description: 'Require or disallow the `Record` type.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-indexed-object-style** for documentation.
|
||||
|
||||
TypeScript supports defining arbitrary object keys using an index signature or mapped type.
|
||||
TypeScript also has a builtin type named `Record` to create an empty object defining only an index signature.
|
||||
For example, the following types are equal:
|
||||
|
||||
```ts
|
||||
interface IndexSignatureInterface {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
type IndexSignatureType = {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
type MappedType = {
|
||||
[key in string]: unknown;
|
||||
};
|
||||
|
||||
type RecordType = Record<string, unknown>;
|
||||
```
|
||||
|
||||
Using one declaration form consistently improves code readability.
|
||||
|
||||
## Options
|
||||
|
||||
- `'record'` _(default)_: only allow the `Record` type.
|
||||
- `'index-signature'`: only allow index signatures.
|
||||
|
||||
### `'record'`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"record"'
|
||||
interface IndexSignatureInterface {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
type IndexSignatureType = {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
type MappedType = {
|
||||
[key in string]: unknown;
|
||||
};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"record"'
|
||||
type RecordType = Record<string, unknown>;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `'index-signature'`
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"index-signature"'
|
||||
type RecordType = Record<string, unknown>;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"index-signature"'
|
||||
interface IndexSignatureInterface {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
type IndexSignatureType = {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
type MappedType = {
|
||||
[key in string]: unknown;
|
||||
};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
This rule is purely a stylistic rule for maintaining consistency in your project.
|
||||
You can turn it off if you don't want to keep a consistent style for indexed object types.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
51
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-return.mdx
generated
vendored
51
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-return.mdx
generated
vendored
|
|
@ -1,51 +0,0 @@
|
|||
---
|
||||
description: 'Require `return` statements to either always or never specify values.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-return** for documentation.
|
||||
|
||||
It adds support for functions that return `void` or `Promise<void>`.
|
||||
|
||||
:::danger warning
|
||||
If possible, it is recommended to use tsconfig's [`noImplicitReturns`](https://www.typescriptlang.org/tsconfig/#noImplicitReturns) option rather than this rule. `noImplicitReturns` is powered by TS's type information and control-flow analysis so it has better coverage than this rule.
|
||||
:::
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
function foo(): undefined {}
|
||||
function bar(flag: boolean): undefined {
|
||||
if (flag) return foo();
|
||||
return;
|
||||
}
|
||||
|
||||
async function baz(flag: boolean): Promise<undefined> {
|
||||
if (flag) return;
|
||||
return foo();
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
function foo(): void {}
|
||||
function bar(flag: boolean): void {
|
||||
if (flag) return foo();
|
||||
return;
|
||||
}
|
||||
|
||||
async function baz(flag: boolean): Promise<void | number> {
|
||||
if (flag) return 42;
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
196
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-assertions.mdx
generated
vendored
196
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-assertions.mdx
generated
vendored
|
|
@ -1,196 +0,0 @@
|
|||
---
|
||||
description: 'Enforce consistent usage of type assertions.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-type-assertions** for documentation.
|
||||
|
||||
TypeScript provides two syntaxes for "type assertions":
|
||||
|
||||
- Angle brackets: `<Type>value`
|
||||
- As: `value as Type`
|
||||
|
||||
This rule aims to standardize the use of type assertion style across the codebase.
|
||||
Keeping to one syntax consistently helps with code readability.
|
||||
|
||||
:::note
|
||||
Type assertions are also commonly referred as "type casting" in TypeScript.
|
||||
However, that term is technically slightly different to what is understood by type casting in other languages.
|
||||
Type assertions are a way to say to the TypeScript compiler, _"I know better than you, it's actually this different type!"_.
|
||||
:::
|
||||
|
||||
[`const` assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions) are always allowed by this rule.
|
||||
Examples of them include `let x = "hello" as const;` and `let x = <const>"hello";`.
|
||||
|
||||
## Options
|
||||
|
||||
### `assertionStyle`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Valid values for `assertionStyle` are:
|
||||
|
||||
- `as` will enforce that you always use `... as foo`.
|
||||
- `angle-bracket` will enforce that you always use `<foo>...`
|
||||
- `never` will enforce that you do not do any type assertions.
|
||||
|
||||
Most codebases will want to enforce not using `angle-bracket` style because it conflicts with JSX syntax, and is confusing when paired with generic syntax.
|
||||
|
||||
Some codebases like to go for an extra level of type safety, and ban assertions altogether via the `never` option.
|
||||
|
||||
### `objectLiteralTypeAssertions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
For example, this would prefer `const x: T = { ... };` to `const x = { ... } as T;` (or similar with angle brackets).
|
||||
The type assertion in the latter case is either unnecessary or will probably hide an error.
|
||||
|
||||
The compiler will warn for excess properties with this syntax, but not missing _required_ fields. For example: `const x: { foo: number } = {};` will fail to compile, but `const x = {} as { foo: number }` will succeed.
|
||||
|
||||
The const assertion `const x = { foo: 1 } as const`, introduced in TypeScript 3.4, is considered beneficial and is ignored by this option.
|
||||
|
||||
Assertions to `any` are also ignored by this option.
|
||||
|
||||
Examples of code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "never" }'
|
||||
const x = { foo: 1 } as T;
|
||||
|
||||
function bar() {
|
||||
return { foo: 1 } as T;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "never" }'
|
||||
const x: T = { foo: 1 };
|
||||
const y = { foo: 1 } as any;
|
||||
const z = { foo: 1 } as unknown;
|
||||
|
||||
function bar(): T {
|
||||
return { foo: 1 };
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Examples of code for `{ assertionStyle: 'as', objectLiteralTypeAssertions: 'allow-as-parameter' }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "allow-as-parameter" }'
|
||||
const x = { foo: 1 } as T;
|
||||
|
||||
function bar() {
|
||||
return { foo: 1 } as T;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```tsx option='{ "assertionStyle": "as", "objectLiteralTypeAssertions": "allow-as-parameter" }'
|
||||
const x: T = { foo: 1 };
|
||||
const y = { foo: 1 } as any;
|
||||
const z = { foo: 1 } as unknown;
|
||||
bar({ foo: 1 } as T);
|
||||
new Clazz({ foo: 1 } as T);
|
||||
function bar() {
|
||||
throw { foo: 1 } as Foo;
|
||||
}
|
||||
const foo = <Foo props={{ bar: 1 } as Bar} />;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `arrayLiteralTypeAssertions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
For example, this would prefer `const x: T[] = [ ... ];` to `const x = [ ... ] as T[];` (or similar with angle brackets).
|
||||
|
||||
The compiler will warn for excess properties of elements with this syntax, but not missing _required_ fields of those objects.
|
||||
For example: `const x: {foo: number}[] = [{}];` will fail to compile, but `const x = [{}] as [{ foo: number }]` will succeed.
|
||||
|
||||
The const assertion `const x = [1, 2, 3] as const`, introduced in TypeScript 3.4, is considered beneficial and is ignored by this option.
|
||||
|
||||
Assertions to `any` are also ignored by this option.
|
||||
|
||||
Examples of code for `{ assertionStyle: 'as', arrayLiteralTypeAssertions: 'never' }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "assertionStyle": "as", "arrayLiteralTypeAssertions": "never" }'
|
||||
const x = ['foo'] as T;
|
||||
|
||||
function bar() {
|
||||
return ['foo'] as T;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "assertionStyle": "as", "arrayLiteralTypeAssertions": "never" }'
|
||||
const x: T = ['foo'];
|
||||
const y = ['foo'] as any;
|
||||
const z = ['foo'] as unknown;
|
||||
|
||||
function bar(): T {
|
||||
return ['foo'];
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Examples of code for `{ assertionStyle: 'as', arrayLiteralTypeAssertions: 'allow-as-parameter' }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "assertionStyle": "as", "arrayLiteralTypeAssertions": "allow-as-parameter" }'
|
||||
const x = ['foo'] as T;
|
||||
|
||||
function bar() {
|
||||
return ['foo'] as T;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```tsx option='{ "assertionStyle": "as", "arrayLiteralTypeAssertions": "allow-as-parameter" }'
|
||||
const x: T = ['foo'];
|
||||
const y = ['foo'] as any;
|
||||
const z = ['foo'] as unknown;
|
||||
bar(['foo'] as T);
|
||||
new Clazz(['foo'] as T);
|
||||
function bar() {
|
||||
throw ['foo'] as Foo;
|
||||
}
|
||||
const foo = <Foo props={['foo'] as Bar} />;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you do not want to enforce consistent type assertions.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
133
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-definitions.mdx
generated
vendored
133
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-definitions.mdx
generated
vendored
|
|
@ -1,133 +0,0 @@
|
|||
---
|
||||
description: 'Enforce type definitions to consistently use either `interface` or `type`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-type-definitions** for documentation.
|
||||
|
||||
TypeScript provides two common ways to define an object type: `interface` and `type`.
|
||||
|
||||
```ts
|
||||
// type alias
|
||||
type T1 = {
|
||||
a: string;
|
||||
b: number;
|
||||
};
|
||||
|
||||
// interface keyword
|
||||
interface T2 {
|
||||
a: string;
|
||||
b: number;
|
||||
}
|
||||
```
|
||||
|
||||
The two are generally very similar, and can often be used interchangeably.
|
||||
Using the same type declaration style consistently helps with code readability.
|
||||
|
||||
## Options
|
||||
|
||||
- `'interface'` _(default)_: enforce using `interface`s for object type definitions.
|
||||
- `'type'`: enforce using `type`s for object type definitions.
|
||||
|
||||
### `'interface'`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"interface"'
|
||||
type T = { x: number };
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"interface"'
|
||||
type T = string;
|
||||
type Foo = string | {};
|
||||
|
||||
interface T {
|
||||
x: number;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `'type'`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"type"'
|
||||
interface T {
|
||||
x: number;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"type"'
|
||||
type T = { x: number };
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## FAQs
|
||||
|
||||
### What are the differences between `interface` and `type`?
|
||||
|
||||
There are very few differences between interfaces and object types in TypeScript.
|
||||
Other than type aliases being used to represent union types, it is rare that you will need to choose one over the other.
|
||||
|
||||
| Feature | Interfaces | Object Types | Explanation |
|
||||
| --------------------- | ---------- | ------------ | ------------------------------------------------------------------------------------------------------ |
|
||||
| Object shapes | ✅ | ✅ | Both can be used to represent general object shapes. |
|
||||
| General performance | ✅ | ✅ | Both are optimized for performance in TypeScript's type checker. |
|
||||
| Edge case performance | ✅ | | Large, complex logical types can be optimized better with interfaces by TypeScript's type checker. |
|
||||
| Traditional semantics | ✅ | | Interfaces are typically the default in much -though not all- of the TypeScript community. |
|
||||
| Non-object shapes | | ✅ | Object types may describe literals, primitives, unions, and intersections. |
|
||||
| Logical types | | ✅ | Object types may include conditional and mapped types. |
|
||||
| Merging | Allowed | Not allowed | Interfaces of the same name are treated as one interface ("merged"); type aliases may not share names. |
|
||||
|
||||
We recommend choosing one definition style, using it when possible, and falling back to the other style when needed.
|
||||
The benefits of remaining consistent within a codebase almost always outweigh the benefits of either definition style.
|
||||
|
||||
### When do the performance differences between `interface` and `type` matter?
|
||||
|
||||
Almost never.
|
||||
Most TypeScript projects do not -and should not- utilize types that exercise the performance differences between the two kinds of definitions.
|
||||
|
||||
If you are having problems with type checking performance, see the [TypeScript Wiki's Performance page](https://github.com/microsoft/TypeScript/wiki/Performance).
|
||||
|
||||
### Why is the default `interface`?
|
||||
|
||||
Interfaces are the prevailing, most common style in the TypeScript.
|
||||
`interface` has traditionally been TypeScript's intended ("semantic") way to convey _"an object with these fields"_.
|
||||
|
||||
We generally recommend staying with the default, `'interface'`, to be stylistically consistent with the majority of TypeScript projects.
|
||||
If you strongly prefer `'type'`, that's fine too.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you specifically want to manually choose whether to use an interface or type literal for stylistic reasons each time you define a type, you can avoid this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
|
||||
You might occasionally need to a different definition type in specific cases, such as if your project is a dependency or dependent of another project that relies on a specific type definition style.
|
||||
Consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [TypeScript Handbook > Everyday Types > Differences Between Type Aliases and Interfaces](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces)
|
||||
- [StackOverflow: Interfaces vs Types in TypeScript](https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript)
|
||||
97
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-exports.mdx
generated
vendored
97
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-exports.mdx
generated
vendored
|
|
@ -1,97 +0,0 @@
|
|||
---
|
||||
description: 'Enforce consistent usage of type exports.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-type-exports** for documentation.
|
||||
|
||||
TypeScript allows specifying a `type` keyword on exports to indicate that the export exists only in the type system, not at runtime.
|
||||
This allows transpilers to drop exports without knowing the types of the dependencies.
|
||||
|
||||
> See [Blog > Consistent Type Exports and Imports: Why and How](/blog/consistent-type-imports-and-exports-why-and-how) for more details.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
interface ButtonProps {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
class Button implements ButtonProps {
|
||||
onClick = () => console.log('button!');
|
||||
}
|
||||
|
||||
export { Button, ButtonProps };
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
interface ButtonProps {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
class Button implements ButtonProps {
|
||||
onClick = () => console.log('button!');
|
||||
}
|
||||
|
||||
export { Button };
|
||||
export type { ButtonProps };
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `fixMixedExportsWithInlineTypeSpecifier`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
If you are using a TypeScript version less than 4.5, then you will not be able to use this option.
|
||||
|
||||
For example the following code:
|
||||
|
||||
```ts
|
||||
const x = 1;
|
||||
type T = number;
|
||||
|
||||
export { x, T };
|
||||
```
|
||||
|
||||
With `{fixMixedExportsWithInlineTypeSpecifier: true}` will be fixed to:
|
||||
|
||||
```ts
|
||||
const x = 1;
|
||||
type T = number;
|
||||
|
||||
export { x, type T };
|
||||
```
|
||||
|
||||
With `{fixMixedExportsWithInlineTypeSpecifier: false}` will be fixed to:
|
||||
|
||||
```ts
|
||||
const x = 1;
|
||||
type T = number;
|
||||
|
||||
export type { T };
|
||||
export { x };
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you use `--isolatedModules` the compiler would error if a type is not re-exported using `export type`.
|
||||
This rule may be less useful in those cases.
|
||||
|
||||
If you specifically want to use both export kinds for stylistic reasons, or don't wish to enforce one style over the other, you can avoid this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
139
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-imports.mdx
generated
vendored
139
node_modules/@typescript-eslint/eslint-plugin/docs/rules/consistent-type-imports.mdx
generated
vendored
|
|
@ -1,139 +0,0 @@
|
|||
---
|
||||
description: 'Enforce consistent usage of type imports.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/consistent-type-imports** for documentation.
|
||||
|
||||
TypeScript allows specifying a `type` keyword on imports to indicate that the export exists only in the type system, not at runtime.
|
||||
This allows transpilers to drop imports without knowing the types of the dependencies.
|
||||
|
||||
> See [Blog > Consistent Type Exports and Imports: Why and How](/blog/consistent-type-imports-and-exports-why-and-how) for more details.
|
||||
|
||||
## Options
|
||||
|
||||
### `prefer`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Valid values for `prefer` are:
|
||||
|
||||
- `type-imports` will enforce that you always use `import type Foo from '...'` except referenced by metadata of decorators. It is the default.
|
||||
- `no-type-imports` will enforce that you always use `import Foo from '...'`.
|
||||
|
||||
Examples of **correct** code with `{prefer: 'type-imports'}`, and **incorrect** code with `{prefer: 'no-type-imports'}`.
|
||||
|
||||
```ts option='{ "prefer": "type-imports" }' showPlaygroundButton
|
||||
import type { Foo } from 'Foo';
|
||||
import type Bar from 'Bar';
|
||||
type T = Foo;
|
||||
const x: Bar = 1;
|
||||
```
|
||||
|
||||
Examples of **incorrect** code with `{prefer: 'type-imports'}`, and **correct** code with `{prefer: 'no-type-imports'}`.
|
||||
|
||||
```ts option='{ "prefer": "type-imports" }' showPlaygroundButton
|
||||
import { Foo } from 'Foo';
|
||||
import Bar from 'Bar';
|
||||
type T = Foo;
|
||||
const x: Bar = 1;
|
||||
```
|
||||
|
||||
### `fixStyle`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Valid values for `fixStyle` are:
|
||||
|
||||
- `separate-type-imports` will add the type keyword after the import keyword `import type { A } from '...'`. It is the default.
|
||||
- `inline-type-imports` will inline the type keyword `import { type A } from '...'` and is only available in TypeScript 4.5 and onwards. See [documentation here](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#type-modifiers-on-import-names 'TypeScript 4.5 documentation on type modifiers and import names').
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
import { Foo } from 'Foo';
|
||||
import Bar from 'Bar';
|
||||
type T = Foo;
|
||||
const x: Bar = 1;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ With `separate-type-imports`">
|
||||
|
||||
```ts option='{ "fixStyle": "separate-type-imports" }'
|
||||
import type { Foo } from 'Foo';
|
||||
import type Bar from 'Bar';
|
||||
type T = Foo;
|
||||
const x: Bar = 1;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ With `inline-type-imports`">
|
||||
|
||||
```ts option='{ "fixStyle": "inline-type-imports" }'
|
||||
import { type Foo } from 'Foo';
|
||||
import type Bar from 'Bar';
|
||||
type T = Foo;
|
||||
const x: Bar = 1;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `disallowTypeAnnotations`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of **incorrect** code with `{disallowTypeAnnotations: true}`:
|
||||
|
||||
```ts option='{ "disallowTypeAnnotations": true }' showPlaygroundButton
|
||||
type T = import('Foo').Foo;
|
||||
const x: import('Bar') = 1;
|
||||
```
|
||||
|
||||
## Caveat: `@decorators` + `experimentalDecorators: true` + `emitDecoratorMetadata: true`
|
||||
|
||||
:::note
|
||||
If you are using `experimentalDecorators: false` (eg [TypeScript v5.0's stable decorators](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html#decorators)) then the rule will always report errors as expected.
|
||||
This caveat **only** applies to `experimentalDecorators: true`
|
||||
:::
|
||||
|
||||
The rule will **_not_** report any errors in files _that contain decorators_ when **both** `experimentalDecorators` and `emitDecoratorMetadata` are turned on.
|
||||
|
||||
> See [Blog > Changes to consistent-type-imports when used with legacy decorators and decorator metadata](/blog/changes-to-consistent-type-imports-with-decorators) for more details.
|
||||
|
||||
If you are using [type-aware linting](/getting-started/typed-linting) then we will automatically infer your setup from your tsconfig and you should not need to configure anything.
|
||||
Otherwise you can explicitly tell our tooling to analyze your code as if the compiler option was turned on by setting both [`parserOptions.emitDecoratorMetadata = true`](/packages/parser/#emitdecoratormetadata) and [`parserOptions.experimentalDecorators = true`](/packages/parser/#experimentaldecorators).
|
||||
|
||||
## Comparison with `importsNotUsedAsValues` / `verbatimModuleSyntax`
|
||||
|
||||
[`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax) was introduced in TypeScript v5.0 (as a replacement for `importsNotUsedAsValues`).
|
||||
This rule and `verbatimModuleSyntax` _mostly_ behave in the same way.
|
||||
There are a few behavior differences:
|
||||
| Situation | `consistent-type-imports` (ESLint) | `verbatimModuleSyntax` (TypeScript) |
|
||||
| -------------------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| Unused imports | Ignored (consider using [`@typescript-eslint/no-unused-vars`](/rules/no-unused-vars)) | Type error |
|
||||
| Usage with `emitDecoratorMetadata` & `experimentalDecorations` | Ignores files that contain decorators | Reports on files that contain decorators |
|
||||
| Failures detected | Does not fail `tsc` build; can be auto-fixed with `--fix` | Fails `tsc` build; cannot be auto-fixed on the command-line |
|
||||
| `import { type T } from 'T';` | TypeScript will emit nothing (it "elides" the import) | TypeScript emits `import {} from 'T'` |
|
||||
|
||||
Because there are some differences, using both this rule and `verbatimModuleSyntax` at the same time can lead to conflicting errors.
|
||||
As such we recommend that you only ever use one _or_ the other -- never both.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you specifically want to use both import kinds for stylistic reasons, or don't wish to enforce one style over the other, you can avoid this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`no-import-type-side-effects`](./no-import-type-side-effects.mdx)
|
||||
- [`import/consistent-type-specifier-style`](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/consistent-type-specifier-style.md)
|
||||
- [`import/no-duplicates` with `{"prefer-inline": true}`](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-duplicates.md#inline-type-imports)
|
||||
59
node_modules/@typescript-eslint/eslint-plugin/docs/rules/default-param-last.mdx
generated
vendored
59
node_modules/@typescript-eslint/eslint-plugin/docs/rules/default-param-last.mdx
generated
vendored
|
|
@ -1,59 +0,0 @@
|
|||
---
|
||||
description: 'Enforce default parameters to be last.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/default-param-last** for documentation.
|
||||
|
||||
It adds support for optional parameters.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
function f(a = 0, b: number) {}
|
||||
function f(a: number, b = 0, c: number) {}
|
||||
function f(a: number, b?: number, c: number) {}
|
||||
class Foo {
|
||||
constructor(
|
||||
public a = 10,
|
||||
private b: number,
|
||||
) {}
|
||||
}
|
||||
class Foo {
|
||||
constructor(
|
||||
public a?: number,
|
||||
private b: number,
|
||||
) {}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
function f(a = 0) {}
|
||||
function f(a: number, b = 0) {}
|
||||
function f(a: number, b?: number) {}
|
||||
function f(a: number, b?: number, c = 0) {}
|
||||
function f(a: number, b = 0, c?: number) {}
|
||||
class Foo {
|
||||
constructor(
|
||||
public a,
|
||||
private b = 0,
|
||||
) {}
|
||||
}
|
||||
class Foo {
|
||||
constructor(
|
||||
public a,
|
||||
private b?: number,
|
||||
) {}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
94
node_modules/@typescript-eslint/eslint-plugin/docs/rules/dot-notation.mdx
generated
vendored
94
node_modules/@typescript-eslint/eslint-plugin/docs/rules/dot-notation.mdx
generated
vendored
|
|
@ -1,94 +0,0 @@
|
|||
---
|
||||
description: 'Enforce dot notation whenever possible.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/dot-notation** for documentation.
|
||||
|
||||
It adds:
|
||||
|
||||
- Support for optionally ignoring computed `private` and/or `protected` member access.
|
||||
- Compatibility with TypeScript's `noPropertyAccessFromIndexSignature` option.
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
interface Options extends BaseDotNotationOptions {
|
||||
allowPrivateClassPropertyAccess?: boolean;
|
||||
allowProtectedClassPropertyAccess?: boolean;
|
||||
allowIndexSignaturePropertyAccess?: boolean;
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
...baseDotNotationDefaultOptions,
|
||||
allowPrivateClassPropertyAccess: false,
|
||||
allowProtectedClassPropertyAccess: false,
|
||||
allowIndexSignaturePropertyAccess: false,
|
||||
};
|
||||
```
|
||||
|
||||
If the TypeScript compiler option `noPropertyAccessFromIndexSignature` is set to `true`, then this rule always allows the use of square bracket notation to access properties of types that have a `string` index signature, even if `allowIndexSignaturePropertyAccess` is `false`.
|
||||
|
||||
### `allowPrivateClassPropertyAccess`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This can be useful because TypeScript will report a type error on dot notation but not array notation.
|
||||
|
||||
Example of a correct code when `allowPrivateClassPropertyAccess` is set to `true`:
|
||||
|
||||
```ts option='{ "allowPrivateClassPropertyAccess": true }' showPlaygroundButton
|
||||
class X {
|
||||
private priv_prop = 123;
|
||||
}
|
||||
|
||||
const x = new X();
|
||||
x['priv_prop'] = 123;
|
||||
```
|
||||
|
||||
### `allowProtectedClassPropertyAccess`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This can be useful because TypeScript will report a type error on dot notation but not array notation.
|
||||
|
||||
Example of a correct code when `allowProtectedClassPropertyAccess` is set to `true`:
|
||||
|
||||
```ts option='{ "allowProtectedClassPropertyAccess": true }' showPlaygroundButton
|
||||
class X {
|
||||
protected protected_prop = 123;
|
||||
}
|
||||
|
||||
const x = new X();
|
||||
x['protected_prop'] = 123;
|
||||
```
|
||||
|
||||
### `allowIndexSignaturePropertyAccess`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Example of correct code when `allowIndexSignaturePropertyAccess` is set to `true`:
|
||||
|
||||
```ts option='{ "allowIndexSignaturePropertyAccess": true }' showPlaygroundButton
|
||||
class X {
|
||||
[key: string]: number;
|
||||
}
|
||||
|
||||
const x = new X();
|
||||
x['hello'] = 123;
|
||||
```
|
||||
|
||||
If the TypeScript compiler option `noPropertyAccessFromIndexSignature` is set to `true`, then the above code is always allowed, even if `allowIndexSignaturePropertyAccess` is `false`.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you specifically want to use both member access kinds for stylistic reasons, or don't wish to enforce one style over the other, you can avoid this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
359
node_modules/@typescript-eslint/eslint-plugin/docs/rules/explicit-function-return-type.mdx
generated
vendored
359
node_modules/@typescript-eslint/eslint-plugin/docs/rules/explicit-function-return-type.mdx
generated
vendored
|
|
@ -1,359 +0,0 @@
|
|||
---
|
||||
description: 'Require explicit return types on functions and class methods.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/explicit-function-return-type** for documentation.
|
||||
|
||||
Functions in TypeScript often don't need to be given an explicit return type annotation.
|
||||
Leaving off the return type is less code to read or write and allows the compiler to infer it from the contents of the function.
|
||||
|
||||
However, explicit return types do make it visually more clear what type is returned by a function.
|
||||
They can also speed up TypeScript type checking performance in large codebases with many large functions.
|
||||
|
||||
This rule enforces that functions do have an explicit return type annotation.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// Should indicate that no value is returned (void)
|
||||
function test() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Should indicate that a number is returned
|
||||
var fn = function () {
|
||||
return 1;
|
||||
};
|
||||
|
||||
// Should indicate that a string is returned
|
||||
var arrowFn = () => 'test';
|
||||
|
||||
class Test {
|
||||
// Should indicate that no value is returned (void)
|
||||
method() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// No return value should be expected (void)
|
||||
function test(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
// A return value of type number
|
||||
var fn = function (): number {
|
||||
return 1;
|
||||
};
|
||||
|
||||
// A return value of type string
|
||||
var arrowFn = (): string => 'test';
|
||||
|
||||
class Test {
|
||||
// No return value should be expected (void)
|
||||
method(): void {
|
||||
return;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### Configuring in a mixed JS/TS codebase
|
||||
|
||||
If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"rules": {
|
||||
// disable the rule for all files
|
||||
"@typescript-eslint/explicit-function-return-type": "off",
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
// enable the rule specifically for TypeScript files
|
||||
"files": ["*.ts", "*.mts", "*.cts", "*.tsx"],
|
||||
"rules": {
|
||||
"@typescript-eslint/explicit-function-return-type": "error",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### `allowExpressions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowExpressions: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowExpressions": true }'
|
||||
function test() {}
|
||||
|
||||
const fn = () => {};
|
||||
|
||||
export default () => {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowExpressions": true }'
|
||||
node.addEventListener('click', () => {});
|
||||
|
||||
node.addEventListener('click', function () {});
|
||||
|
||||
const foo = arr.map(i => i * i);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowTypedFunctionExpressions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowTypedFunctionExpressions: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowTypedFunctionExpressions": true }'
|
||||
let arrowFn = () => 'test';
|
||||
|
||||
let funcExpr = function () {
|
||||
return 'test';
|
||||
};
|
||||
|
||||
let objectProp = {
|
||||
foo: () => 1,
|
||||
};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowTypedFunctionExpressions": true }'
|
||||
type FuncType = () => string;
|
||||
|
||||
let arrowFn: FuncType = () => 'test';
|
||||
|
||||
let funcExpr: FuncType = function () {
|
||||
return 'test';
|
||||
};
|
||||
|
||||
let asTyped = (() => '') as () => string;
|
||||
|
||||
interface ObjectType {
|
||||
foo(): number;
|
||||
}
|
||||
let objectProp: ObjectType = {
|
||||
foo: () => 1,
|
||||
};
|
||||
let objectPropAs = {
|
||||
foo: () => 1,
|
||||
} as ObjectType;
|
||||
|
||||
declare function functionWithArg(arg: () => number);
|
||||
functionWithArg(() => 1);
|
||||
|
||||
declare function functionWithObjectArg(arg: { method: () => number });
|
||||
functionWithObjectArg({
|
||||
method() {
|
||||
return 1;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowHigherOrderFunctions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowHigherOrderFunctions: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowHigherOrderFunctions": true }'
|
||||
var arrowFn = () => () => {};
|
||||
|
||||
function fn() {
|
||||
return function () {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowHigherOrderFunctions": true }'
|
||||
var arrowFn = () => (): void => {};
|
||||
|
||||
function fn() {
|
||||
return function (): void {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowDirectConstAssertionInArrowFunctions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowDirectConstAssertionInArrowFunctions: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowDirectConstAssertionInArrowFunctions": true }'
|
||||
const func = (value: number) => ({ type: 'X', value }) as any;
|
||||
const func = (value: number) => ({ type: 'X', value }) as Action;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowDirectConstAssertionInArrowFunctions": true }'
|
||||
const func = (value: number) => ({ foo: 'bar', value }) as const;
|
||||
const func = () => x as const;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowConciseArrowFunctionExpressionsStartingWithVoid`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowConciseArrowFunctionExpressionsStartingWithVoid: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowConciseArrowFunctionExpressionsStartingWithVoid": true }'
|
||||
var join = (a: string, b: string) => `${a}${b}`;
|
||||
|
||||
const log = (message: string) => {
|
||||
console.log(message);
|
||||
};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowConciseArrowFunctionExpressionsStartingWithVoid": true }'
|
||||
var log = (message: string) => void console.log(message);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowFunctionsWithoutTypeParameters`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowFunctionsWithoutTypeParameters: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowFunctionsWithoutTypeParameters": true }'
|
||||
function foo<T>(t: T) {
|
||||
return t;
|
||||
}
|
||||
|
||||
const bar = <T>(t: T) => t;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowFunctionsWithoutTypeParameters": true }'
|
||||
function foo<T>(t: T): T {
|
||||
return t;
|
||||
}
|
||||
|
||||
const bar = <T>(t: T): T => t;
|
||||
|
||||
function allowedFunction(x: string) {
|
||||
return x;
|
||||
}
|
||||
|
||||
const allowedArrow = (x: string) => x;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowedNames`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
You may pass function/method names you would like this rule to ignore, like so:
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/explicit-function-return-type": [
|
||||
"error",
|
||||
{
|
||||
"allowedNames": ["ignoredFunctionName", "ignoredMethodName"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `allowIIFEs`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowIIFEs: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowIIFEs": true }'
|
||||
var func = () => 'foo';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowIIFEs": true }'
|
||||
var foo = (() => 'foo')();
|
||||
|
||||
var bar = (function () {
|
||||
return 'bar';
|
||||
})();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't find the added cost of explicitly writing function return types to be worth the visual clarity, or your project is not large enough for it to be a factor in type checking performance, then you will not need this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- TypeScript [Functions](https://www.typescriptlang.org/docs/handbook/functions.html#function-types)
|
||||
353
node_modules/@typescript-eslint/eslint-plugin/docs/rules/explicit-member-accessibility.mdx
generated
vendored
353
node_modules/@typescript-eslint/eslint-plugin/docs/rules/explicit-member-accessibility.mdx
generated
vendored
|
|
@ -1,353 +0,0 @@
|
|||
---
|
||||
description: 'Require explicit accessibility modifiers on class properties and methods.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/explicit-member-accessibility** for documentation.
|
||||
|
||||
TypeScript allows placing explicit `public`, `protected`, and `private` accessibility modifiers in front of class members.
|
||||
The modifiers exist solely in the type system and just serve to describe who is allowed to access those members.
|
||||
|
||||
Leaving off accessibility modifiers makes for less code to read and write.
|
||||
Members are `public` by default.
|
||||
|
||||
However, adding in explicit accessibility modifiers can be helpful in codebases with many classes for enforcing proper privacy of members.
|
||||
Some developers also find it preferable for code readability to keep member publicity explicit.
|
||||
|
||||
## Examples
|
||||
|
||||
This rule aims to make code more readable and explicit about who can use
|
||||
which properties.
|
||||
|
||||
## Options
|
||||
|
||||
### Configuring in a mixed JS/TS codebase
|
||||
|
||||
If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"rules": {
|
||||
// disable the rule for all files
|
||||
"@typescript-eslint/explicit-member-accessibility": "off",
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
// enable the rule specifically for TypeScript files
|
||||
"files": ["*.ts", "*.mts", "*.cts", "*.tsx"],
|
||||
"rules": {
|
||||
"@typescript-eslint/explicit-member-accessibility": "error",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### `accessibility`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This rule in its default state requires no configuration and will enforce that every class member has an accessibility modifier. If you would like to allow for some implicit public members then you have the following options:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"accessibility": "explicit",
|
||||
"overrides": {
|
||||
"accessors": "explicit",
|
||||
"constructors": "no-public",
|
||||
"methods": "explicit",
|
||||
"properties": "off",
|
||||
"parameterProperties": "explicit",
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Note the above is an example of a possible configuration you could use - it is not the default configuration.
|
||||
|
||||
The following patterns are considered incorrect code if no options are provided:
|
||||
|
||||
```ts showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(name) {
|
||||
// No accessibility modifier
|
||||
this.animalName = name;
|
||||
}
|
||||
animalName: string; // No accessibility modifier
|
||||
get name(): string {
|
||||
// No accessibility modifier
|
||||
return this.animalName;
|
||||
}
|
||||
set name(value: string) {
|
||||
// No accessibility modifier
|
||||
this.animalName = value;
|
||||
}
|
||||
walk() {
|
||||
// method
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The following patterns are considered correct with the default options `{ accessibility: 'explicit' }`:
|
||||
|
||||
```ts option='{ "accessibility": "explicit" }' showPlaygroundButton
|
||||
class Animal {
|
||||
public constructor(
|
||||
public breed,
|
||||
name,
|
||||
) {
|
||||
// Parameter property and constructor
|
||||
this.animalName = name;
|
||||
}
|
||||
private animalName: string; // Property
|
||||
get name(): string {
|
||||
// get accessor
|
||||
return this.animalName;
|
||||
}
|
||||
set name(value: string) {
|
||||
// set accessor
|
||||
this.animalName = value;
|
||||
}
|
||||
public walk() {
|
||||
// method
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The following patterns are considered incorrect with the accessibility set to **no-public** `[{ accessibility: 'no-public' }]`:
|
||||
|
||||
```ts option='{ "accessibility": "no-public" }' showPlaygroundButton
|
||||
class Animal {
|
||||
public constructor(
|
||||
public breed,
|
||||
name,
|
||||
) {
|
||||
// Parameter property and constructor
|
||||
this.animalName = name;
|
||||
}
|
||||
public animalName: string; // Property
|
||||
public get name(): string {
|
||||
// get accessor
|
||||
return this.animalName;
|
||||
}
|
||||
public set name(value: string) {
|
||||
// set accessor
|
||||
this.animalName = value;
|
||||
}
|
||||
public walk() {
|
||||
// method
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The following patterns are considered correct with the accessibility set to **no-public** `[{ accessibility: 'no-public' }]`:
|
||||
|
||||
```ts option='{ "accessibility": "no-public" }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(
|
||||
protected breed,
|
||||
name,
|
||||
) {
|
||||
// Parameter property and constructor
|
||||
this.name = name;
|
||||
}
|
||||
private animalName: string; // Property
|
||||
get name(): string {
|
||||
// get accessor
|
||||
return this.animalName;
|
||||
}
|
||||
private set name(value: string) {
|
||||
// set accessor
|
||||
this.animalName = value;
|
||||
}
|
||||
protected walk() {
|
||||
// method
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `overrides`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
There are three ways in which an override can be used.
|
||||
|
||||
- To disallow the use of public on a given member.
|
||||
- To enforce explicit member accessibility when the root has allowed implicit public accessibility
|
||||
- To disable any checks on given member type
|
||||
|
||||
#### Disallow the use of public on a given member
|
||||
|
||||
e.g. `[ { overrides: { constructors: 'no-public' } } ]`
|
||||
|
||||
The following patterns are considered incorrect with the example override
|
||||
|
||||
```ts option='{ "overrides": { "constructors": "no-public" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
public constructor(protected animalName) {}
|
||||
public get name() {
|
||||
return this.animalName;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The following patterns are considered correct with the example override
|
||||
|
||||
```ts option='{ "overrides": { "constructors": "no-public" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(protected animalName) {}
|
||||
public get name() {
|
||||
return this.animalName;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Require explicit accessibility for a given member
|
||||
|
||||
e.g. `[ { accessibility: 'no-public', overrides: { properties: 'explicit' } } ]`
|
||||
|
||||
The following patterns are considered incorrect with the example override
|
||||
|
||||
```ts option='{ "accessibility": "no-public", "overrides": { "properties": "explicit" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(protected animalName) {}
|
||||
get name() {
|
||||
return this.animalName;
|
||||
}
|
||||
protected set name(value: string) {
|
||||
this.animalName = value;
|
||||
}
|
||||
legs: number;
|
||||
private hasFleas: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
The following patterns are considered correct with the example override
|
||||
|
||||
```ts option='{ "accessibility": "no-public", "overrides": { "properties": "explicit" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(protected animalName) {}
|
||||
get name() {
|
||||
return this.animalName;
|
||||
}
|
||||
protected set name(value: string) {
|
||||
this.animalName = value;
|
||||
}
|
||||
public legs: number;
|
||||
private hasFleas: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
e.g. `[ { accessibility: 'off', overrides: { parameterProperties: 'explicit' } } ]`
|
||||
|
||||
The following code is considered incorrect with the example override
|
||||
|
||||
```ts option='{ "accessibility": "off", "overrides": { "parameterProperties": "explicit" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(readonly animalName: string) {}
|
||||
}
|
||||
```
|
||||
|
||||
The following code patterns are considered correct with the example override
|
||||
|
||||
```ts option='{ "accessibility": "off", "overrides": { "parameterProperties": "explicit" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(public readonly animalName: string) {}
|
||||
}
|
||||
|
||||
class Animal {
|
||||
constructor(public animalName: string) {}
|
||||
}
|
||||
|
||||
class Animal {
|
||||
constructor(animalName: string) {}
|
||||
}
|
||||
```
|
||||
|
||||
e.g. `[ { accessibility: 'off', overrides: { parameterProperties: 'no-public' } } ]`
|
||||
|
||||
The following code is considered incorrect with the example override
|
||||
|
||||
```ts option='{ "accessibility": "off", "overrides": { "parameterProperties": "no-public" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(public readonly animalName: string) {}
|
||||
}
|
||||
```
|
||||
|
||||
The following code is considered correct with the example override
|
||||
|
||||
```ts option='{ "accessibility": "off", "overrides": { "parameterProperties": "no-public" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(public animalName: string) {}
|
||||
}
|
||||
```
|
||||
|
||||
#### Disable any checks on given member type
|
||||
|
||||
e.g. `[{ overrides: { accessors : 'off' } } ]`
|
||||
|
||||
As no checks on the overridden member type are performed all permutations of visibility are permitted for that member type
|
||||
|
||||
The follow pattern is considered incorrect for the given configuration
|
||||
|
||||
```ts option='{ "overrides": { "accessors" : "off" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
constructor(protected animalName) {}
|
||||
public get name() {
|
||||
return this.animalName;
|
||||
}
|
||||
get legs() {
|
||||
return this.legCount;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The following patterns are considered correct with the example override
|
||||
|
||||
```ts option='{ "overrides": { "accessors" : "off" } }' showPlaygroundButton
|
||||
class Animal {
|
||||
public constructor(protected animalName) {}
|
||||
public get name() {
|
||||
return this.animalName;
|
||||
}
|
||||
get legs() {
|
||||
return this.legCount;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `ignoredMethodNames`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Note that this option does not care about context, and will ignore every method with these names, which could lead to it missing some cases. You should use this sparingly.
|
||||
e.g. `[ { ignoredMethodNames: ['specificMethod', 'whateverMethod'] } ]`
|
||||
|
||||
```ts option='{ "ignoredMethodNames": ["specificMethod", "whateverMethod"] }' showPlaygroundButton
|
||||
class Animal {
|
||||
get specificMethod() {
|
||||
console.log('No error because you specified this method on option');
|
||||
}
|
||||
get whateverMethod() {
|
||||
console.log('No error because you specified this method on option');
|
||||
}
|
||||
public get otherMethod() {
|
||||
console.log('This method comply with this rule');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you think defaulting to public is a good default, then you should consider using the `no-public` setting.
|
||||
If you want to mix implicit and explicit public members then you can disable this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- TypeScript [Accessibility Modifiers Handbook Docs](https://www.typescriptlang.org/docs/handbook/2/classes.html#member-visibility)
|
||||
287
node_modules/@typescript-eslint/eslint-plugin/docs/rules/explicit-module-boundary-types.mdx
generated
vendored
287
node_modules/@typescript-eslint/eslint-plugin/docs/rules/explicit-module-boundary-types.mdx
generated
vendored
|
|
@ -1,287 +0,0 @@
|
|||
---
|
||||
description: "Require explicit return and argument types on exported functions' and classes' public class methods."
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/explicit-module-boundary-types** for documentation.
|
||||
|
||||
Explicit types for function return values and arguments makes it clear to any calling code what is the module boundary's input and output.
|
||||
Adding explicit type annotations for those types can help improve code readability.
|
||||
It can also improve TypeScript type checking performance on larger codebases.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// Should indicate that no value is returned (void)
|
||||
export function test() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Should indicate that a string is returned
|
||||
export var arrowFn = () => 'test';
|
||||
|
||||
// All arguments should be typed
|
||||
export var arrowFn = (arg): string => `test ${arg}`;
|
||||
export var arrowFn = (arg: any): string => `test ${arg}`;
|
||||
|
||||
export class Test {
|
||||
// Should indicate that no value is returned (void)
|
||||
method() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// A function with no return value (void)
|
||||
export function test(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
// A return value of type string
|
||||
export var arrowFn = (): string => 'test';
|
||||
|
||||
// All arguments should be typed
|
||||
export var arrowFn = (arg: string): string => `test ${arg}`;
|
||||
export var arrowFn = (arg: unknown): string => `test ${arg}`;
|
||||
|
||||
export class Test {
|
||||
// A class method with no return value (void)
|
||||
method(): void {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// The function does not apply because it is not an exported function.
|
||||
function test() {
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### Configuring in a mixed JS/TS codebase
|
||||
|
||||
If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"rules": {
|
||||
// disable the rule for all files
|
||||
"@typescript-eslint/explicit-module-boundary-types": "off",
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
// enable the rule specifically for TypeScript files
|
||||
"files": ["*.ts", "*.mts", "*.cts", "*.tsx"],
|
||||
"rules": {
|
||||
"@typescript-eslint/explicit-module-boundary-types": "error",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### `allowArgumentsExplicitlyTypedAsAny`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowArgumentsExplicitlyTypedAsAny: false }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowArgumentsExplicitlyTypedAsAny": false }'
|
||||
export const func = (value: any): number => value + 1;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowArgumentsExplicitlyTypedAsAny": true }'
|
||||
export const func = (value: any): number => value + 1;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowDirectConstAssertionInArrowFunctions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowDirectConstAssertionInArrowFunctions: false }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowDirectConstAssertionInArrowFunctions": false }'
|
||||
export const func = (value: number) => ({ type: 'X', value });
|
||||
export const foo = () => ({
|
||||
bar: true,
|
||||
});
|
||||
export const bar = () => 1;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowDirectConstAssertionInArrowFunctions": true }'
|
||||
export const func = (value: number) => ({ type: 'X', value }) as const;
|
||||
export const foo = () =>
|
||||
({
|
||||
bar: true,
|
||||
}) as const;
|
||||
export const bar = () => 1 as const;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowedNames`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
You may pass function/method names you would like this rule to ignore, like so:
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/explicit-module-boundary-types": [
|
||||
"error",
|
||||
{
|
||||
"allowedNames": ["ignoredFunctionName", "ignoredMethodName"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `allowHigherOrderFunctions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowHigherOrderFunctions: false }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowHigherOrderFunctions": false }'
|
||||
export const arrowFn = () => () => {};
|
||||
|
||||
export function fn() {
|
||||
return function () {};
|
||||
}
|
||||
|
||||
export function foo(outer: string) {
|
||||
return function (inner: string) {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowHigherOrderFunctions": true }'
|
||||
export const arrowFn = () => (): void => {};
|
||||
|
||||
export function fn() {
|
||||
return function (): void {};
|
||||
}
|
||||
|
||||
export function foo(outer: string) {
|
||||
return function (inner: string): void {};
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowTypedFunctionExpressions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `{ allowTypedFunctionExpressions: false }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowTypedFunctionExpressions": false }'
|
||||
export let arrowFn = () => 'test';
|
||||
|
||||
export let funcExpr = function () {
|
||||
return 'test';
|
||||
};
|
||||
|
||||
export let objectProp = {
|
||||
foo: () => 1,
|
||||
};
|
||||
|
||||
export const foo = bar => {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowTypedFunctionExpressions": true }'
|
||||
type FuncType = () => string;
|
||||
|
||||
export let arrowFn: FuncType = () => 'test';
|
||||
|
||||
export let funcExpr: FuncType = function () {
|
||||
return 'test';
|
||||
};
|
||||
|
||||
export let asTyped = (() => '') as () => string;
|
||||
|
||||
interface ObjectType {
|
||||
foo(): number;
|
||||
}
|
||||
export let objectProp: ObjectType = {
|
||||
foo: () => 1,
|
||||
};
|
||||
export let objectPropAs = {
|
||||
foo: () => 1,
|
||||
} as ObjectType;
|
||||
|
||||
type FooType = (bar: string) => void;
|
||||
export const foo: FooType = bar => {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowOverloadFunctions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of correct code when `allowOverloadFunctions` is set to `true`:
|
||||
|
||||
```ts option='{ "allowOverloadFunctions": true }' showPlaygroundButton
|
||||
export function test(a: string): string;
|
||||
export function test(a: number): number;
|
||||
export function test(a: unknown) {
|
||||
return a;
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project is not used by downstream consumers that are sensitive to API types, you can disable this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- TypeScript [Functions](https://www.typescriptlang.org/docs/handbook/functions.html#function-types)
|
||||
|
||||
## Related To
|
||||
|
||||
- [explicit-function-return-type](./explicit-function-return-type.mdx)
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/func-call-spacing.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/func-call-spacing.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/indent.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/indent.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
12
node_modules/@typescript-eslint/eslint-plugin/docs/rules/init-declarations.mdx
generated
vendored
12
node_modules/@typescript-eslint/eslint-plugin/docs/rules/init-declarations.mdx
generated
vendored
|
|
@ -1,12 +0,0 @@
|
|||
---
|
||||
description: 'Require or disallow initialization in variable declarations.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/init-declarations** for documentation.
|
||||
|
||||
It adds support for TypeScript's `declare` variables.
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/key-spacing.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/key-spacing.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/keyword-spacing.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/keyword-spacing.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/lines-around-comment.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/lines-around-comment.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/lines-between-class-members.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/lines-between-class-members.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
54
node_modules/@typescript-eslint/eslint-plugin/docs/rules/max-params.mdx
generated
vendored
54
node_modules/@typescript-eslint/eslint-plugin/docs/rules/max-params.mdx
generated
vendored
|
|
@ -1,54 +0,0 @@
|
|||
---
|
||||
description: 'Enforce a maximum number of parameters in function definitions.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/max-params** for documentation.
|
||||
|
||||
It adds support for TypeScript `this` parameters so they won't be counted as a parameter.
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
interface Options extends BaseMaxParamsOptions {
|
||||
countVoidThis?: boolean;
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
...baseMaxParamsOptions,
|
||||
countVoidThis: false,
|
||||
};
|
||||
```
|
||||
|
||||
### `countVoidThis`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Example of a code when `countVoidThis` is set to `false` and `max` is `1`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "countVoidThis": false, "max": 1 }'
|
||||
function hasNoThis(this: void, first: string, second: string) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "countVoidThis": false, "max": 1 }'
|
||||
function hasNoThis(this: void, first: string) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/member-delimiter-style.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/member-delimiter-style.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
1483
node_modules/@typescript-eslint/eslint-plugin/docs/rules/member-ordering.mdx
generated
vendored
1483
node_modules/@typescript-eslint/eslint-plugin/docs/rules/member-ordering.mdx
generated
vendored
File diff suppressed because it is too large
Load diff
124
node_modules/@typescript-eslint/eslint-plugin/docs/rules/method-signature-style.mdx
generated
vendored
124
node_modules/@typescript-eslint/eslint-plugin/docs/rules/method-signature-style.mdx
generated
vendored
|
|
@ -1,124 +0,0 @@
|
|||
---
|
||||
description: 'Enforce using a particular method signature syntax.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/method-signature-style** for documentation.
|
||||
|
||||
TypeScript provides two ways to define an object/interface function property:
|
||||
|
||||
```ts
|
||||
interface Example {
|
||||
// method shorthand syntax
|
||||
func(arg: string): number;
|
||||
|
||||
// regular property with function type
|
||||
func: (arg: string) => number;
|
||||
}
|
||||
```
|
||||
|
||||
The two are very similar; most of the time it doesn't matter which one you use.
|
||||
|
||||
A good practice is to use the TypeScript's `strict` option (which implies `strictFunctionTypes`) which enables correct typechecking for function properties only (method signatures get old behavior).
|
||||
|
||||
TypeScript FAQ:
|
||||
|
||||
> A method and a function property of the same type behave differently.
|
||||
> Methods are always bivariant in their argument, while function properties are contravariant in their argument under `strictFunctionTypes`.
|
||||
|
||||
See the reasoning behind that in the [TypeScript PR for the compiler option](https://github.com/microsoft/TypeScript/pull/18654).
|
||||
|
||||
## Options
|
||||
|
||||
This rule accepts one string option:
|
||||
|
||||
- `"property"`: Enforce using property signature for functions. Use this to enforce maximum correctness together with TypeScript's strict mode.
|
||||
- `"method"`: Enforce using method signature for functions. Use this if you aren't using TypeScript's strict mode and prefer this style.
|
||||
|
||||
### `property`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code with `property` option.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"property"'
|
||||
interface T1 {
|
||||
func(arg: string): number;
|
||||
}
|
||||
type T2 = {
|
||||
func(arg: boolean): void;
|
||||
};
|
||||
interface T3 {
|
||||
func(arg: number): void;
|
||||
func(arg: string): void;
|
||||
func(arg: boolean): void;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"property"'
|
||||
interface T1 {
|
||||
func: (arg: string) => number;
|
||||
}
|
||||
type T2 = {
|
||||
func: (arg: boolean) => void;
|
||||
};
|
||||
// this is equivalent to the overload
|
||||
interface T3 {
|
||||
func: ((arg: number) => void) &
|
||||
((arg: string) => void) &
|
||||
((arg: boolean) => void);
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `method`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code with `method` option.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='"method"'
|
||||
interface T1 {
|
||||
func: (arg: string) => number;
|
||||
}
|
||||
type T2 = {
|
||||
func: (arg: boolean) => void;
|
||||
};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='"method"'
|
||||
interface T1 {
|
||||
func(arg: string): number;
|
||||
}
|
||||
type T2 = {
|
||||
func(arg: boolean): void;
|
||||
};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't want to enforce a particular style for object/interface function types, and/or if you don't use `strictFunctionTypes`, then you don't need this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend picking a single option for this rule that works best for your project.
|
||||
755
node_modules/@typescript-eslint/eslint-plugin/docs/rules/naming-convention.mdx
generated
vendored
755
node_modules/@typescript-eslint/eslint-plugin/docs/rules/naming-convention.mdx
generated
vendored
|
|
@ -1,755 +0,0 @@
|
|||
---
|
||||
description: 'Enforce naming conventions for everything across a codebase.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/naming-convention** for documentation.
|
||||
|
||||
Enforcing naming conventions helps keep the codebase consistent, and reduces overhead when thinking about how to name a variable.
|
||||
Additionally, a well-designed style guide can help communicate intent, such as by enforcing all private properties begin with an `_`, and all global-level constants are written in `UPPER_CASE`.
|
||||
|
||||
:::note
|
||||
This rule is _feature frozen_: it will no longer receive new features such as new options.
|
||||
It still will accept bug and documentation fixes for its existing area of features and to support new TypeScript versions.
|
||||
|
||||
Stylistic rules that enforce naming and/or sorting conventions tend to grow incomprehensibly complex as increasingly obscure features are requested.
|
||||
This rule has reached the limit of what is reasonable for the typescript-eslint project to maintain.
|
||||
See [eslint-plugin: Feature freeze naming and sorting stylistic rules](https://github.com/typescript-eslint/typescript-eslint/issues/8792) for more information.
|
||||
:::
|
||||
|
||||
## Examples
|
||||
|
||||
This rule allows you to enforce conventions for any identifier, using granular selectors to create a fine-grained style guide.
|
||||
|
||||
:::note
|
||||
|
||||
This rule only needs type information in specific cases, detailed below.
|
||||
|
||||
:::
|
||||
|
||||
## Options
|
||||
|
||||
This rule accepts an array of objects, with each object describing a different naming convention.
|
||||
Each property will be described in detail below. Also see the examples section below for illustrated examples.
|
||||
|
||||
```ts
|
||||
type Options = {
|
||||
// format options
|
||||
format:
|
||||
| (
|
||||
| 'camelCase'
|
||||
| 'strictCamelCase'
|
||||
| 'PascalCase'
|
||||
| 'StrictPascalCase'
|
||||
| 'snake_case'
|
||||
| 'UPPER_CASE'
|
||||
)[]
|
||||
| null;
|
||||
custom?: {
|
||||
regex: string;
|
||||
match: boolean;
|
||||
};
|
||||
leadingUnderscore?:
|
||||
| 'forbid'
|
||||
| 'require'
|
||||
| 'requireDouble'
|
||||
| 'allow'
|
||||
| 'allowDouble'
|
||||
| 'allowSingleOrDouble';
|
||||
trailingUnderscore?:
|
||||
| 'forbid'
|
||||
| 'require'
|
||||
| 'requireDouble'
|
||||
| 'allow'
|
||||
| 'allowDouble'
|
||||
| 'allowSingleOrDouble';
|
||||
prefix?: string[];
|
||||
suffix?: string[];
|
||||
|
||||
// selector options
|
||||
selector: Selector | Selector[];
|
||||
filter?:
|
||||
| string
|
||||
| {
|
||||
regex: string;
|
||||
match: boolean;
|
||||
};
|
||||
// the allowed values for these are dependent on the selector - see below
|
||||
modifiers?: Modifiers<Selector>[];
|
||||
types?: Types<Selector>[];
|
||||
}[];
|
||||
|
||||
// the default config is similar to ESLint's camelcase rule but more strict
|
||||
const defaultOptions: Options = [
|
||||
{
|
||||
selector: 'default',
|
||||
format: ['camelCase'],
|
||||
leadingUnderscore: 'allow',
|
||||
trailingUnderscore: 'allow',
|
||||
},
|
||||
|
||||
{
|
||||
selector: 'import',
|
||||
format: ['camelCase', 'PascalCase'],
|
||||
},
|
||||
|
||||
{
|
||||
selector: 'variable',
|
||||
format: ['camelCase', 'UPPER_CASE'],
|
||||
leadingUnderscore: 'allow',
|
||||
trailingUnderscore: 'allow',
|
||||
},
|
||||
|
||||
{
|
||||
selector: 'typeLike',
|
||||
format: ['PascalCase'],
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
### Format Options
|
||||
|
||||
Every single selector can have the same set of format options.
|
||||
For information about how each selector is applied, see ["How does the rule evaluate a name's format?"](#how-does-the-rule-evaluate-a-names-format).
|
||||
|
||||
#### `format`
|
||||
|
||||
The `format` option defines the allowed formats for the identifier. This option accepts an array of the following values, and the identifier can match any of them:
|
||||
|
||||
- `camelCase` - standard camelCase format - no underscores are allowed between characters, and consecutive capitals are allowed (i.e. both `myID` and `myId` are valid).
|
||||
- `PascalCase` - same as `camelCase`, except the first character must be upper-case.
|
||||
- `snake_case` - standard snake_case format - all characters must be lower-case, and underscores are allowed.
|
||||
- `strictCamelCase` - same as `camelCase`, but consecutive capitals are not allowed (i.e. `myId` is valid, but `myID` is not).
|
||||
- `StrictPascalCase` - same as `strictCamelCase`, except the first character must be upper-case.
|
||||
- `UPPER_CASE` - same as `snake_case`, except all characters must be upper-case.
|
||||
|
||||
Instead of an array, you may also pass `null`. This signifies "this selector shall not have its format checked".
|
||||
This can be useful if you want to enforce no particular format for a specific selector, after applying a group selector.
|
||||
|
||||
#### `custom`
|
||||
|
||||
The `custom` option defines a custom regex that the identifier must (or must not) match. This option allows you to have a bit more finer-grained control over identifiers, letting you ban (or force) certain patterns and substrings.
|
||||
Accepts an object with the following properties:
|
||||
|
||||
- `match` - true if the identifier _must_ match the `regex`, false if the identifier _must not_ match the `regex`.
|
||||
- `regex` - a string that is then passed into RegExp to create a new regular expression: `new RegExp(regex)`
|
||||
|
||||
#### `filter`
|
||||
|
||||
The `filter` option operates similar to `custom`, accepting the same shaped object, except that it controls if the rest of the configuration should or should not be applied to an identifier.
|
||||
|
||||
You can use this to include or exclude specific identifiers from specific configurations.
|
||||
|
||||
Accepts an object with the following properties:
|
||||
|
||||
- `match` - true if the identifier _must_ match the `regex`, false if the identifier _must not_ match the `regex`.
|
||||
- `regex` - a string that is then passed into RegExp to create a new regular expression: `new RegExp(regex)`
|
||||
|
||||
Alternatively, `filter` accepts a regular expression (anything accepted into `new RegExp(filter)`). In this case, it's treated as if you had passed an object with the regex and `match: true`.
|
||||
|
||||
#### `leadingUnderscore` / `trailingUnderscore`
|
||||
|
||||
The `leadingUnderscore` / `trailingUnderscore` options control whether leading/trailing underscores are considered valid. Accepts one of the following values:
|
||||
|
||||
- `allow` - existence of a single leading/trailing underscore is not explicitly enforced.
|
||||
- `allowDouble` - existence of a double leading/trailing underscore is not explicitly enforced.
|
||||
- `allowSingleOrDouble` - existence of a single or a double leading/trailing underscore is not explicitly enforced.
|
||||
- `forbid` - a leading/trailing underscore is not allowed at all.
|
||||
- `require` - a single leading/trailing underscore must be included.
|
||||
- `requireDouble` - two leading/trailing underscores must be included.
|
||||
|
||||
#### `prefix` / `suffix`
|
||||
|
||||
The `prefix` / `suffix` options control which prefix/suffix strings must exist for the identifier. Accepts an array of strings.
|
||||
|
||||
If these are provided, the identifier must start with one of the provided values. For example, if you provide `{ prefix: ['Class', 'IFace', 'Type'] }`, then the following names are valid: `ClassBar`, `IFaceFoo`, `TypeBaz`, but the name `Bang` is not valid, as it contains none of the prefixes.
|
||||
|
||||
**Note:** As [documented above](#format-options), the prefix is trimmed before format is validated, therefore PascalCase must be used to allow variables such as `isEnabled` using the prefix `is`.
|
||||
|
||||
### Selector Options
|
||||
|
||||
- `selector` allows you to specify what types of identifiers to target.
|
||||
- Accepts one or array of selectors to define an option block that applies to one or multiple selectors.
|
||||
- For example, if you provide `{ selector: ['function', 'variable'] }`, then it will apply the same option to variable and function nodes.
|
||||
- See [Allowed Selectors, Modifiers and Types](#allowed-selectors-modifiers-and-types) below for the complete list of allowed selectors.
|
||||
- `modifiers` allows you to specify which modifiers to granularly apply to, such as the accessibility (`#private`/`private`/`protected`/`public`), or if the thing is `static`, etc.
|
||||
- The name must match _all_ of the modifiers.
|
||||
- For example, if you provide `{ modifiers: ['private','readonly','static'] }`, then it will only match something that is `private static readonly`, and something that is just `private` will not match.
|
||||
- The following `modifiers` are allowed:
|
||||
- `abstract`,`override`,`private`,`protected`,`readonly`,`static` - matches any member explicitly declared with the given modifier.
|
||||
- `async` - matches any method, function, or function variable which is async via the `async` keyword (e.g. does not match functions that return promises without using `async` keyword)
|
||||
- `const` - matches a variable declared as being `const` (`const x = 1`).
|
||||
- `destructured` - matches a variable declared via an object destructuring pattern (`const {x, z = 2}`).
|
||||
- Note that this does not match renamed destructured properties (`const {x: y, a: b = 2}`).
|
||||
- `exported` - matches anything that is exported from the module.
|
||||
- `global` - matches a variable/function declared in the top-level scope.
|
||||
- `#private` - matches any member with a private identifier (an identifier that starts with `#`)
|
||||
- `public` - matches any member that is either explicitly declared as `public`, or has no visibility modifier (i.e. implicitly public).
|
||||
- `requiresQuotes` - matches any name that requires quotes as it is not a valid identifier (i.e. has a space, a dash, etc in it).
|
||||
- `unused` - matches anything that is not used.
|
||||
- `types` allows you to specify which types to match. This option supports simple, primitive types only (`array`,`boolean`,`function`,`number`,`string`).
|
||||
- The name must match _one_ of the types.
|
||||
- **_NOTE - Using this option will require that you lint with type information._**
|
||||
- For example, this lets you do things like enforce that `boolean` variables are prefixed with a verb.
|
||||
- The following `types` are allowed:
|
||||
- `array` matches any type assignable to `Array<unknown> | null | undefined`
|
||||
- `boolean` matches any type assignable to `boolean | null | undefined`
|
||||
- `function` matches any type assignable to `Function | null | undefined`
|
||||
- `number` matches any type assignable to `number | null | undefined`
|
||||
- `string` matches any type assignable to `string | null | undefined`
|
||||
|
||||
The ordering of selectors does not matter. The implementation will automatically sort the selectors to ensure they match from most-specific to least specific. It will keep checking selectors in that order until it finds one that matches the name. See ["How does the rule automatically order selectors?"](#how-does-the-rule-automatically-order-selectors)
|
||||
|
||||
#### Allowed Selectors, Modifiers and Types
|
||||
|
||||
There are two types of selectors, individual selectors, and grouped selectors.
|
||||
|
||||
##### Individual Selectors
|
||||
|
||||
Individual Selectors match specific, well-defined sets. There is no overlap between each of the individual selectors.
|
||||
|
||||
- `classicAccessor` - matches any accessor. It refers to the methods attached to `get` and `set` syntax.
|
||||
- Allowed `modifiers`: `abstract`, `override`, `private`, `protected`, `public`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `autoAccessor` - matches any auto-accessor. An auto-accessor is just a class field starting with an `accessor` keyword.
|
||||
- Allowed `modifiers`: `abstract`, `override`, `private`, `protected`, `public`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `class` - matches any class declaration.
|
||||
- Allowed `modifiers`: `abstract`, `exported`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `classMethod` - matches any class method. Also matches properties that have direct function expression or arrow function expression values. Does not match accessors.
|
||||
- Allowed `modifiers`: `abstract`, `async`, `override`, `#private`, `private`, `protected`, `public`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: none.
|
||||
- `classProperty` - matches any class property. Does not match properties that have direct function expression or arrow function expression values.
|
||||
- Allowed `modifiers`: `abstract`, `override`, `#private`, `private`, `protected`, `public`, `readonly`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `enum` - matches any enum declaration.
|
||||
- Allowed `modifiers`: `exported`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `enumMember` - matches any enum member.
|
||||
- Allowed `modifiers`: `requiresQuotes`.
|
||||
- Allowed `types`: none.
|
||||
- `function` - matches any named function declaration or named function expression.
|
||||
- Allowed `modifiers`: `async`, `exported`, `global`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `import` - matches namespace imports and default imports (i.e. does not match named imports).
|
||||
- Allowed `modifiers`: `default`, `namespace`.
|
||||
- Allowed `types`: none.
|
||||
- `interface` - matches any interface declaration.
|
||||
- Allowed `modifiers`: `exported`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `objectLiteralMethod` - matches any object literal method. Also matches properties that have direct function expression or arrow function expression values. Does not match accessors.
|
||||
- Allowed `modifiers`: `async`, `public`, `requiresQuotes`.
|
||||
- Allowed `types`: none.
|
||||
- `objectLiteralProperty` - matches any object literal property. Does not match properties that have direct function expression or arrow function expression values.
|
||||
- Allowed `modifiers`: `public`, `requiresQuotes`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `parameter` - matches any function parameter. Does not match parameter properties.
|
||||
- Allowed `modifiers`: `destructured`, `unused`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `parameterProperty` - matches any parameter property.
|
||||
- Allowed `modifiers`: `private`, `protected`, `public`, `readonly`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `typeAlias` - matches any type alias declaration.
|
||||
- Allowed `modifiers`: `exported`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `typeMethod` - matches any object type method. Also matches properties that have direct function expression or arrow function expression values. Does not match accessors.
|
||||
- Allowed `modifiers`: `public`, `requiresQuotes`.
|
||||
- Allowed `types`: none.
|
||||
- `typeParameter` - matches any generic type parameter declaration.
|
||||
- Allowed `modifiers`: `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `typeProperty` - matches any object type property. Does not match properties that have direct function expression or arrow function expression values.
|
||||
- Allowed `modifiers`: `public`, `readonly`, `requiresQuotes`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `variable` - matches any `const` / `let` / `var` variable name.
|
||||
- Allowed `modifiers`: `async`, `const`, `destructured`, `exported`, `global`, `unused`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
|
||||
##### Group Selectors
|
||||
|
||||
Group Selectors are provided for convenience, and essentially bundle up sets of individual selectors.
|
||||
|
||||
- `default` - matches everything.
|
||||
- Allowed `modifiers`: all modifiers.
|
||||
- Allowed `types`: none.
|
||||
- `accessor` - matches the same as `classicAccessor` and `autoAccessor`.
|
||||
- Allowed `modifiers`: `abstract`, `override`, `private`, `protected`, `public`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `memberLike` - matches the same as `classicAccessor`, `autoAccessor`, `enumMember`, `method`, `parameterProperty`, `property`.
|
||||
- Allowed `modifiers`: `abstract`, `async`, `override`, `#private`, `private`, `protected`, `public`, `readonly`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: none.
|
||||
- `method` - matches the same as `classMethod`, `objectLiteralMethod`, `typeMethod`.
|
||||
- Allowed `modifiers`: `abstract`, `async`, `override`, `#private`, `private`, `protected`, `public`, `readonly`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: none.
|
||||
- `property` - matches the same as `classProperty`, `objectLiteralProperty`, `typeProperty`.
|
||||
- Allowed `modifiers`: `abstract`, `async`, `override`, `#private`, `private`, `protected`, `public`, `readonly`, `requiresQuotes`, `static`.
|
||||
- Allowed `types`: `array`, `boolean`, `function`, `number`, `string`.
|
||||
- `typeLike` - matches the same as `class`, `enum`, `interface`, `typeAlias`, `typeParameter`.
|
||||
- Allowed `modifiers`: `abstract`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
- `variableLike` - matches the same as `function`, `parameter` and `variable`.
|
||||
- Allowed `modifiers`: `async`, `unused`.
|
||||
- Allowed `types`: none.
|
||||
|
||||
## FAQ
|
||||
|
||||
This is a big rule, and there's a lot of docs. Here are a few clarifications that people often ask about or figure out via trial-and-error.
|
||||
|
||||
### How does the rule evaluate a selector?
|
||||
|
||||
Each selector is checked in the following way:
|
||||
|
||||
1. check the `filter`
|
||||
1. if `filter` is omitted → skip this step.
|
||||
2. if the name matches the `filter` → continue evaluating this selector.
|
||||
3. if the name does not match the `filter` → skip this selector and continue to the next selector.
|
||||
2. check the `selector`
|
||||
1. if `selector` is one individual selector → the name's type must be of that type.
|
||||
2. if `selector` is a group selector → the name's type must be one of the grouped types.
|
||||
3. if `selector` is an array of selectors → apply the above for each selector in the array.
|
||||
3. check the `types`
|
||||
1. if `types` is omitted → skip this step.
|
||||
2. if the name has a type in `types` → continue evaluating this selector.
|
||||
3. if the name does not have a type in `types` → skip this selector and continue to the next selector.
|
||||
|
||||
A name is considered to pass the config if it:
|
||||
|
||||
1. Matches one selector and passes all of that selector's format checks.
|
||||
2. Matches no selectors.
|
||||
|
||||
A name is considered to fail the config if it matches one selector and fails one that selector's format checks.
|
||||
|
||||
### How does the rule automatically order selectors?
|
||||
|
||||
Each identifier should match exactly one selector. It may match multiple group selectors - but only ever one selector.
|
||||
With that in mind - the base sort order works out to be:
|
||||
|
||||
1. Individual Selectors
|
||||
2. Grouped Selectors
|
||||
3. Default Selector
|
||||
|
||||
Within each of these categories, some further sorting occurs based on what selector options are supplied:
|
||||
|
||||
1. `filter` is given the highest priority above all else.
|
||||
2. `types`
|
||||
3. `modifiers`
|
||||
4. everything else
|
||||
|
||||
For example, if you provide the following config:
|
||||
|
||||
```ts
|
||||
[
|
||||
/* 1 */ { selector: 'default', format: ['camelCase'] },
|
||||
/* 2 */ { selector: 'variable', format: ['snake_case'] },
|
||||
/* 3 */ { selector: 'variable', types: ['boolean'], format: ['UPPER_CASE'] },
|
||||
/* 4 */ { selector: 'variableLike', format: ['PascalCase'] },
|
||||
];
|
||||
```
|
||||
|
||||
Then for the code `const x = 1`, the rule will validate the selectors in the following order: `3`, `2`, `4`, `1`.
|
||||
To clearly spell it out:
|
||||
|
||||
- (3) is tested first because it has `types` and is an individual selector.
|
||||
- (2) is tested next because it is an individual selector.
|
||||
- (4) is tested next as it is a grouped selector.
|
||||
- (1) is tested last as it is the base default selector.
|
||||
|
||||
Its worth noting that whilst this order is applied, all selectors may not run on a name.
|
||||
This is explained in ["How does the rule evaluate a name's format?"](#how-does-the-rule-evaluate-a-names-format)
|
||||
|
||||
### How does the rule evaluate a name's format?
|
||||
|
||||
When the format of an identifier is checked, it is checked in the following order:
|
||||
|
||||
1. validate leading underscore
|
||||
1. validate trailing underscore
|
||||
1. validate prefix
|
||||
1. validate suffix
|
||||
1. validate custom
|
||||
1. validate format
|
||||
|
||||
For steps 1-4, if the identifier matches the option, the matching part will be removed.
|
||||
This is done so that you can apply formats like PascalCase without worrying about prefixes or underscores causing it to not match.
|
||||
|
||||
One final note is that if the name were to become empty via this trimming process, it is considered to match all `format`s. An example of where this might be useful is for generic type parameters, where you want all names to be prefixed with `T`, but also want to allow for the single character `T` name.
|
||||
|
||||
Here are some examples to help illustrate
|
||||
|
||||
Name: `_IMyInterface`
|
||||
Selector:
|
||||
|
||||
```json
|
||||
{
|
||||
"leadingUnderscore": "require",
|
||||
"prefix": ["I"],
|
||||
"format": ["UPPER_CASE", "StrictPascalCase"]
|
||||
}
|
||||
```
|
||||
|
||||
1. `name = _IMyInterface`
|
||||
1. validate leading underscore
|
||||
1. config is provided
|
||||
1. check name → pass
|
||||
1. Trim underscore → `name = IMyInterface`
|
||||
1. validate trailing underscore
|
||||
1. config is not provided → skip
|
||||
1. validate prefix
|
||||
1. config is provided
|
||||
1. check name → pass
|
||||
1. Trim prefix → `name = MyInterface`
|
||||
1. validate suffix
|
||||
1. config is not provided → skip
|
||||
1. validate custom
|
||||
1. config is not provided → skip
|
||||
1. validate format
|
||||
1. for each format...
|
||||
1. `format = 'UPPER_CASE'`
|
||||
1. check format → fail.
|
||||
- Important to note that if you supply multiple formats - the name only needs to match _one_ of them!
|
||||
1. `format = 'StrictPascalCase'`
|
||||
1. check format → success.
|
||||
1. **_success_**
|
||||
|
||||
Name: `IMyInterface`
|
||||
Selector:
|
||||
|
||||
```json
|
||||
{
|
||||
"format": ["StrictPascalCase"],
|
||||
"trailingUnderscore": "allow",
|
||||
"custom": {
|
||||
"regex": "^I[A-Z]",
|
||||
"match": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
1. `name = IMyInterface`
|
||||
1. validate leading underscore
|
||||
1. config is not provided → skip
|
||||
1. validate trailing underscore
|
||||
1. config is provided
|
||||
1. check name → pass
|
||||
1. Trim underscore → `name = IMyInterface`
|
||||
1. validate prefix
|
||||
1. config is not provided → skip
|
||||
1. validate suffix
|
||||
1. config is not provided → skip
|
||||
1. validate custom
|
||||
1. config is provided
|
||||
1. `regex = new RegExp("^I[A-Z]")`
|
||||
1. `regex.test(name) === custom.match`
|
||||
1. **_fail_** → report and exit
|
||||
|
||||
### What happens if I provide a `modifiers` to a Group Selector?
|
||||
|
||||
Some group selectors accept `modifiers`. For the most part these will work exactly the same as with individual selectors.
|
||||
There is one exception to this in that a modifier might not apply to all individual selectors covered by a group selector.
|
||||
|
||||
For example - `memberLike` includes the `enumMember` selector, and it allows the `protected` modifier.
|
||||
An `enumMember` can never ever be `protected`, which means that the following config will never match any `enumMember`:
|
||||
|
||||
```json
|
||||
{
|
||||
"selector": "memberLike",
|
||||
"modifiers": ["protected"]
|
||||
}
|
||||
```
|
||||
|
||||
To help with matching, members that cannot specify an accessibility will always have the `public` modifier. This means that the following config will always match any `enumMember`:
|
||||
|
||||
```json
|
||||
{
|
||||
"selector": "memberLike",
|
||||
"modifiers": ["public"]
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Enforce that all variables, functions and properties follow are camelCase
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{ "selector": "variableLike", "format": ["camelCase"] }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that private members are prefixed with an underscore
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "memberLike",
|
||||
"modifiers": ["private"],
|
||||
"format": ["camelCase"],
|
||||
"leadingUnderscore": "require"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that boolean variables are prefixed with an allowed verb
|
||||
|
||||
**Note:** As [documented above](#format-options), the prefix is trimmed before format is validated, thus PascalCase must be used to allow variables such as `isEnabled`.
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "variable",
|
||||
"types": ["boolean"],
|
||||
"format": ["PascalCase"],
|
||||
"prefix": ["is", "should", "has", "can", "did", "will"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that all variables are either in camelCase or UPPER_CASE
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "variable",
|
||||
"format": ["camelCase", "UPPER_CASE"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that all const variables are in UPPER_CASE
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "variable",
|
||||
"modifiers": ["const"],
|
||||
"format": ["UPPER_CASE"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that type parameters (generics) are prefixed with `T`
|
||||
|
||||
This allows you to emulate the old `generic-type-naming` rule.
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "typeParameter",
|
||||
"format": ["PascalCase"],
|
||||
"prefix": ["T"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that interface names do not begin with an `I`
|
||||
|
||||
This allows you to emulate the old `interface-name-prefix` rule.
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "interface",
|
||||
"format": ["PascalCase"],
|
||||
"custom": {
|
||||
"regex": "^I[A-Z]",
|
||||
"match": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that function names are either in camelCase or PascalCase
|
||||
|
||||
Function names are typically camelCase, but UI library components (especially JSX, such as React and Solid) use PascalCase to distinguish them from intrinsic elements. If you are writing function components, consider allowing both camelCase and PascalCase for functions.
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "function",
|
||||
"format": ["camelCase", "PascalCase"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce that variable and function names are in camelCase
|
||||
|
||||
This allows you to lint multiple type with same pattern.
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": ["variable", "function"],
|
||||
"format": ["camelCase"],
|
||||
"leadingUnderscore": "allow"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Ignore properties that **_require_** quotes
|
||||
|
||||
Sometimes you have to use a quoted name that breaks the convention (for example, HTTP headers).
|
||||
If this is a common thing in your codebase, then you have a few options.
|
||||
|
||||
If you simply want to allow all property names that require quotes, you can use the `requiresQuotes` modifier to match any property name that _requires_ quoting, and use `format: null` to ignore the name.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": [
|
||||
"classProperty",
|
||||
"objectLiteralProperty",
|
||||
"typeProperty",
|
||||
"classMethod",
|
||||
"objectLiteralMethod",
|
||||
"typeMethod",
|
||||
"accessor",
|
||||
"enumMember",
|
||||
],
|
||||
"format": null,
|
||||
"modifiers": ["requiresQuotes"],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
If you have a small and known list of exceptions, you can use the `filter` option to ignore these specific names only:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "property",
|
||||
"format": ["strictCamelCase"],
|
||||
"filter": {
|
||||
// you can expand this regex to add more allowed names
|
||||
"regex": "^(Property-Name-One|Property-Name-Two)$",
|
||||
"match": false,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
You can use the `filter` option to ignore names with specific characters:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "property",
|
||||
"format": ["strictCamelCase"],
|
||||
"filter": {
|
||||
// you can expand this regex as you find more cases that require quoting that you want to allow
|
||||
"regex": "[- ]",
|
||||
"match": false,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
Note that there is no way to ignore any name that is quoted - only names that are required to be quoted.
|
||||
This is intentional - adding quotes around a name is not an escape hatch for proper naming.
|
||||
If you want an escape hatch for a specific name - you should can use an [`eslint-disable` comment](https://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments).
|
||||
|
||||
### Ignore destructured names
|
||||
|
||||
Sometimes you might want to allow destructured properties to retain their original name, even if it breaks your naming convention.
|
||||
|
||||
You can use the `destructured` modifier to match these names, and explicitly set `format: null` to apply no formatting:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "variable",
|
||||
"modifiers": ["destructured"],
|
||||
"format": null,
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Enforce the codebase follows ESLint's `camelcase` conventions
|
||||
|
||||
```json
|
||||
{
|
||||
"camelcase": "off",
|
||||
"@typescript-eslint/naming-convention": [
|
||||
"error",
|
||||
{
|
||||
"selector": "default",
|
||||
"format": ["camelCase"]
|
||||
},
|
||||
|
||||
{
|
||||
"selector": "variable",
|
||||
"format": ["camelCase", "UPPER_CASE"]
|
||||
},
|
||||
{
|
||||
"selector": "parameter",
|
||||
"format": ["camelCase"],
|
||||
"leadingUnderscore": "allow"
|
||||
},
|
||||
|
||||
{
|
||||
"selector": "memberLike",
|
||||
"modifiers": ["private"],
|
||||
"format": ["camelCase"],
|
||||
"leadingUnderscore": "require"
|
||||
},
|
||||
|
||||
{
|
||||
"selector": "typeLike",
|
||||
"format": ["PascalCase"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
This rule can be very strict.
|
||||
If you don't have strong needs for enforcing naming conventions, we recommend using it only to flag very egregious violations of your naming standards.
|
||||
Consider documenting your naming conventions and enforcing them in code review if you have processes like that.
|
||||
|
||||
If you do not want to enforce naming conventions for anything, you can disable this rule.
|
||||
|
||||
However, keep in mind that inconsistent style can harm readability in a project.
|
||||
We recommend that if you care about naming conventions, pick a single option for this rule that works best for your project.
|
||||
34
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-array-constructor.mdx
generated
vendored
34
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-array-constructor.mdx
generated
vendored
|
|
@ -1,34 +0,0 @@
|
|||
---
|
||||
description: 'Disallow generic `Array` constructors.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-array-constructor** for documentation.
|
||||
|
||||
It adds support for the generically typed `Array` constructor (`new Array<Foo>()`).
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
Array(0, 1, 2);
|
||||
new Array(0, 1, 2);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
Array<number>(0, 1, 2);
|
||||
new Array<Foo>(x, y, z);
|
||||
|
||||
Array(500);
|
||||
new Array(someOtherArray.length);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
44
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-array-delete.mdx
generated
vendored
44
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-array-delete.mdx
generated
vendored
|
|
@ -1,44 +0,0 @@
|
|||
---
|
||||
description: 'Disallow using the `delete` operator on array values.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-array-delete** for documentation.
|
||||
|
||||
When using the `delete` operator with an array value, the array's `length` property is not affected,
|
||||
but the element at the specified index is removed and leaves an empty slot in the array.
|
||||
This is likely to lead to unexpected behavior. As mentioned in the
|
||||
[MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#deleting_array_elements),
|
||||
the recommended way to remove an element from an array is by using the
|
||||
[`Array#splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) method.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
declare const arr: number[];
|
||||
|
||||
delete arr[0];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
declare const arr: number[];
|
||||
|
||||
arr.splice(0, 1);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
When you want to allow the delete operator with array expressions.
|
||||
115
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-base-to-string.mdx
generated
vendored
115
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-base-to-string.mdx
generated
vendored
|
|
@ -1,115 +0,0 @@
|
|||
---
|
||||
description: 'Require `.toString()` and `.toLocaleString()` to only be called on objects which provide useful information when stringified.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-base-to-string** for documentation.
|
||||
|
||||
JavaScript will call `toString()` on an object when it is converted to a string, such as when concatenated with a string (`expr + ''`), when interpolated into template literals (`${expr}`), or when passed as an argument to the String constructor (`String(expr)`).
|
||||
The default Object `.toString()` and `toLocaleString()` use the format `"[object Object]"`, which is often not what was intended.
|
||||
This rule reports on stringified values that aren't primitives and don't define a more useful `.toString()` or `toLocaleString()` method.
|
||||
|
||||
> Note that `Function` provides its own `.toString()` and `toLocaleString()` that return the function's code.
|
||||
> Functions are not flagged by this rule.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// Passing an object or class instance to string concatenation:
|
||||
'' + {};
|
||||
|
||||
class MyClass {}
|
||||
const value = new MyClass();
|
||||
value + '';
|
||||
|
||||
// Interpolation and manual .toString() and `toLocaleString()` calls too:
|
||||
`Value: ${value}`;
|
||||
String({});
|
||||
({}).toString();
|
||||
({}).toLocaleString();
|
||||
|
||||
// Stringifying objects or instances in an array with the `Array.prototype.join`.
|
||||
[{}, new MyClass()].join('');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// These types all have useful .toString() and `toLocaleString()` methods
|
||||
'Text' + true;
|
||||
`Value: ${123}`;
|
||||
`Arrays too: ${[1, 2, 3]}`;
|
||||
(() => {}).toString();
|
||||
String(42);
|
||||
(() => {}).toLocaleString();
|
||||
|
||||
// Defining a custom .toString class is considered acceptable
|
||||
class CustomToString {
|
||||
toString() {
|
||||
return 'Hello, world!';
|
||||
}
|
||||
}
|
||||
`Value: ${new CustomToString()}`;
|
||||
|
||||
const literalWithToString = {
|
||||
toString: () => 'Hello, world!',
|
||||
};
|
||||
|
||||
`Value: ${literalWithToString}`;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Alternatives
|
||||
|
||||
Consider using `JSON.stringify` when you want to convert non-primitive things to string for logging, debugging, etc.
|
||||
|
||||
```typescript
|
||||
declare const o: object;
|
||||
const errorMessage = 'Found unexpected value: ' + JSON.stringify(o);
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
### `ignoredTypeNames`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This is useful for types missing `toString()` or `toLocaleString()` (but actually has `toString()` or `toLocaleString()`).
|
||||
There are some types missing `toString()` or `toLocaleString()` in old versions of TypeScript, like `RegExp`, `URL`, `URLSearchParams` etc.
|
||||
|
||||
The following patterns are considered correct with the default options `{ ignoredTypeNames: ["RegExp"] }`:
|
||||
|
||||
```ts option='{ "ignoredTypeNames": ["RegExp"] }' showPlaygroundButton
|
||||
`${/regex/}`;
|
||||
'' + /regex/;
|
||||
/regex/.toString();
|
||||
let value = /regex/;
|
||||
value.toString();
|
||||
let text = `${value}`;
|
||||
String(/regex/);
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't mind a risk of `"[object Object]"` or incorrect type coercions in your values, then you will not need this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`restrict-plus-operands`](./restrict-plus-operands.mdx)
|
||||
- [`restrict-template-expressions`](./restrict-template-expressions.mdx)
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [`Object.prototype.toString()` MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString)
|
||||
- [`Object.prototype.toLocaleString()` MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString)
|
||||
- [Microsoft/TypeScript Add missing toString declarations for base types that have them](https://github.com/microsoft/TypeScript/issues/38347)
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
---
|
||||
description: 'Disallow non-null assertion in locations that may be confusing.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-confusing-non-null-assertion** for documentation.
|
||||
|
||||
Using a non-null assertion (`!`) next to an assignment or equality check (`=` or `==` or `===`) creates code that is confusing as it looks similar to an inequality check (`!=` `!==`).
|
||||
|
||||
```typescript
|
||||
a! == b; // a non-null assertion(`!`) and an equals test(`==`)
|
||||
a !== b; // not equals test(`!==`)
|
||||
a! === b; // a non-null assertion(`!`) and a triple equals test(`===`)
|
||||
```
|
||||
|
||||
Using a non-null assertion (`!`) next to an in test (`in`) or an instanceof test (`instanceof`) creates code that is confusing since it may look like the operator is negated, but it is actually not.
|
||||
|
||||
{/* prettier-ignore */}
|
||||
```typescript
|
||||
a! in b; // a non-null assertion(`!`) and an in test(`in`)
|
||||
a !in b; // also a non-null assertion(`!`) and an in test(`in`)
|
||||
!(a in b); // a negated in test
|
||||
|
||||
a! instanceof b; // a non-null assertion(`!`) and an instanceof test(`instanceof`)
|
||||
a !instanceof b; // also a non-null assertion(`!`) and an instanceof test(`instanceof`)
|
||||
!(a instanceof b); // a negated instanceof test
|
||||
````
|
||||
|
||||
This rule flags confusing `!` assertions and suggests either removing them or wrapping the asserted expression in `()` parenthesis.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
interface Foo {
|
||||
bar?: string;
|
||||
num?: number;
|
||||
}
|
||||
|
||||
const foo: Foo = getFoo();
|
||||
const isEqualsBar = foo.bar! == 'hello';
|
||||
const isEqualsNum = 1 + foo.num! == 2;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
{/* prettier-ignore */}
|
||||
```ts
|
||||
interface Foo {
|
||||
bar?: string;
|
||||
num?: number;
|
||||
}
|
||||
|
||||
const foo: Foo = getFoo();
|
||||
const isEqualsBar = foo.bar == 'hello';
|
||||
const isEqualsNum = (1 + foo.num!) == 2;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't care about this confusion, then you will not need this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [`Issue: Easy misunderstanding: "! ==="`](https://github.com/microsoft/TypeScript/issues/37837) in [TypeScript repo](https://github.com/microsoft/TypeScript)
|
||||
148
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-confusing-void-expression.mdx
generated
vendored
148
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-confusing-void-expression.mdx
generated
vendored
|
|
@ -1,148 +0,0 @@
|
|||
---
|
||||
description: 'Require expressions of type void to appear in statement position.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-confusing-void-expression** for documentation.
|
||||
|
||||
`void` in TypeScript refers to a function return that is meant to be ignored.
|
||||
Attempting to use a `void`-typed value, such as storing the result of a called function in a variable, is often a sign of a programmer error.
|
||||
`void` can also be misleading for other developers even if used correctly.
|
||||
|
||||
This rule prevents `void` type expressions from being used in misleading locations such as being assigned to a variable, provided as a function argument, or returned from a function.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// somebody forgot that `alert` doesn't return anything
|
||||
const response = alert('Are you sure?');
|
||||
console.log(alert('Are you sure?'));
|
||||
|
||||
// it's not obvious whether the chained promise will contain the response (fixable)
|
||||
promise.then(value => window.postMessage(value));
|
||||
|
||||
// it looks like we are returning the result of `console.error` (fixable)
|
||||
function doSomething() {
|
||||
if (!somethingToDo) {
|
||||
return console.error('Nothing to do!');
|
||||
}
|
||||
|
||||
console.log('Doing a thing...');
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// just a regular void function in a statement position
|
||||
alert('Hello, world!');
|
||||
|
||||
// this function returns a boolean value so it's ok
|
||||
const response = confirm('Are you sure?');
|
||||
console.log(confirm('Are you sure?'));
|
||||
|
||||
// now it's obvious that `postMessage` doesn't return any response
|
||||
promise.then(value => {
|
||||
window.postMessage(value);
|
||||
});
|
||||
|
||||
// now it's explicit that we want to log the error and return early
|
||||
function doSomething() {
|
||||
if (!somethingToDo) {
|
||||
console.error('Nothing to do!');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Doing a thing...');
|
||||
}
|
||||
|
||||
// using logical expressions for their side effects is fine
|
||||
cond && console.log('true');
|
||||
cond || console.error('false');
|
||||
cond ? console.log('true') : console.error('false');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `ignoreArrowShorthand`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
It might be undesirable to wrap every arrow function shorthand expression.
|
||||
Especially when using the Prettier formatter, which spreads such code across 3 lines instead of 1.
|
||||
|
||||
Examples of additional **correct** code with this option enabled:
|
||||
|
||||
```ts option='{ "ignoreArrowShorthand": true }' showPlaygroundButton
|
||||
promise.then(value => window.postMessage(value));
|
||||
```
|
||||
|
||||
### `ignoreVoidOperator`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
It might be preferable to only use some distinct syntax
|
||||
to explicitly mark the confusing but valid usage of void expressions.
|
||||
This option allows void expressions which are explicitly wrapped in the `void` operator.
|
||||
This can help avoid confusion among other developers as long as they are made aware of this code style.
|
||||
|
||||
This option also changes the automatic fixes for common cases to use the `void` operator.
|
||||
It also enables a suggestion fix to wrap the void expression with `void` operator for every problem reported.
|
||||
|
||||
Examples of additional **correct** code with this option enabled:
|
||||
|
||||
```ts option='{ "ignoreVoidOperator": true }' showPlaygroundButton
|
||||
// now it's obvious that we don't expect any response
|
||||
promise.then(value => void window.postMessage(value));
|
||||
|
||||
// now it's explicit that we don't want to return anything
|
||||
function doSomething() {
|
||||
if (!somethingToDo) {
|
||||
return void console.error('Nothing to do!');
|
||||
}
|
||||
|
||||
console.log('Doing a thing...');
|
||||
}
|
||||
|
||||
// we are sure that we want to always log `undefined`
|
||||
console.log(void alert('Hello, world!'));
|
||||
```
|
||||
|
||||
### `ignoreVoidReturningFunctions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Some projects prefer allowing functions that explicitly return `void` to return `void` expressions. Doing so allows more writing more succinct functions.
|
||||
|
||||
:::note
|
||||
This is technically risky as the `void`-returning function might actually be returning a value not seen by the type system.
|
||||
:::
|
||||
|
||||
```ts option='{ "ignoreVoidReturningFunctions": true }' showPlaygroundButton
|
||||
function foo(): void {
|
||||
return console.log();
|
||||
}
|
||||
|
||||
function onError(callback: () => void): void {
|
||||
callback();
|
||||
}
|
||||
|
||||
onError(() => console.log('oops'));
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
The return type of a function can be inspected by going to its definition or hovering over it in an IDE.
|
||||
If you don't care about being explicit about the void type in actual code then don't use this rule.
|
||||
Also, if you strongly prefer a concise coding style more strongly than any fear of `void`-related bugs then you can avoid this rule.
|
||||
119
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-deprecated.mdx
generated
vendored
119
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-deprecated.mdx
generated
vendored
|
|
@ -1,119 +0,0 @@
|
|||
---
|
||||
description: 'Disallow using code marked as `@deprecated`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-deprecated** for documentation.
|
||||
|
||||
The [JSDoc `@deprecated` tag](https://jsdoc.app/tags-deprecated) can be used to document some piece of code being deprecated.
|
||||
It's best to avoid using code marked as deprecated.
|
||||
This rule reports on any references to code marked as `@deprecated`.
|
||||
|
||||
:::note
|
||||
[TypeScript recognizes the `@deprecated` tag](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#deprecated), allowing editors to visually indicate deprecated code — usually with a ~strikethrough~.
|
||||
However, TypeScript doesn't report type errors for deprecated code on its own.
|
||||
:::
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
/** @deprecated Use apiV2 instead. */
|
||||
declare function apiV1(): Promise<string>;
|
||||
|
||||
declare function apiV2(): Promise<string>;
|
||||
|
||||
await apiV1();
|
||||
```
|
||||
|
||||
```ts
|
||||
import { parse } from 'node:url';
|
||||
|
||||
// 'parse' is deprecated. Use the WHATWG URL API instead.
|
||||
const url = parse('/foo');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
/** @deprecated Use apiV2 instead. */
|
||||
declare function apiV1(): Promise<string>;
|
||||
|
||||
declare function apiV2(): Promise<string>;
|
||||
|
||||
await apiV2();
|
||||
```
|
||||
|
||||
```ts
|
||||
// Modern Node.js API, uses `new URL()`
|
||||
const url2 = new URL('/foo', 'http://www.example.com');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allow`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This option takes the shared [`TypeOrValueSpecifier` format](/packages/type-utils/type-or-value-specifier).
|
||||
|
||||
Examples of code for this rule with:
|
||||
|
||||
```json
|
||||
{
|
||||
"allow": [
|
||||
{ "from": "file", "name": "apiV1" },
|
||||
{ "from": "lib", "name": "escape" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{"allow":[{"from":"file","name":"apiV1"},{"from":"lib","name":"escape"}]}'
|
||||
/** @deprecated */
|
||||
declare function apiV2(): Promise<string>;
|
||||
|
||||
await apiV2();
|
||||
|
||||
// `unescape` has been deprecated since ES5.
|
||||
unescape('...');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{"allow":[{"from":"file","name":"apiV1"},{"from":"lib","name":"escape"}]}'
|
||||
import { Bar } from 'bar-lib';
|
||||
/** @deprecated */
|
||||
declare function apiV1(): Promise<string>;
|
||||
|
||||
await apiV1();
|
||||
|
||||
// `escape` has been deprecated since ES5.
|
||||
escape('...');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If portions of your project heavily use deprecated APIs and have no plan for moving to non-deprecated ones, you might want to disable this rule in those portions.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`import/no-deprecated`](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-deprecated.md) and [`import-x/no-deprecated`](https://github.com/un-ts/eslint-plugin-import-x/blob/master/docs/rules/no-deprecated.md): Does not use type information, but does also support [TomDoc](http://tomdoc.org)
|
||||
- [`eslint-plugin-deprecation`](https://github.com/gund/eslint-plugin-deprecation) ([`deprecation/deprecation`](https://github.com/gund/eslint-plugin-deprecation?tab=readme-ov-file#rules)): Predecessor to this rule in a separate plugin
|
||||
16
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-dupe-class-members.mdx
generated
vendored
16
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-dupe-class-members.mdx
generated
vendored
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
description: 'Disallow duplicate class members.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-dupe-class-members** for documentation.
|
||||
|
||||
import TypeScriptOverlap from '@site/src/components/TypeScriptOverlap';
|
||||
|
||||
<TypeScriptOverlap />
|
||||
|
||||
It adds support for TypeScript's method overload definitions.
|
||||
66
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-duplicate-enum-values.mdx
generated
vendored
66
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-duplicate-enum-values.mdx
generated
vendored
|
|
@ -1,66 +0,0 @@
|
|||
---
|
||||
description: 'Disallow duplicate enum member values.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-duplicate-enum-values** for documentation.
|
||||
|
||||
Although TypeScript supports duplicate enum member values, people usually expect members to have unique values within the same enum. Duplicate values can lead to bugs that are hard to track down.
|
||||
|
||||
## Examples
|
||||
|
||||
This rule disallows defining an enum with multiple members initialized to the same value.
|
||||
|
||||
> This rule only enforces on enum members initialized with string or number literals.
|
||||
> Members without an initializer or initialized with an expression are not checked by this rule.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
enum E {
|
||||
A = 0,
|
||||
B = 0,
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
enum E {
|
||||
A = 'A',
|
||||
B = 'A',
|
||||
C = `A`,
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
enum E {
|
||||
A = 0,
|
||||
B = 1,
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
enum E {
|
||||
A = 'A',
|
||||
B = 'B',
|
||||
C = `C`,
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
It can sometimes be useful to include duplicate enum members for very specific use cases.
|
||||
For example, when renaming an enum member, it can sometimes be useful to keep the old name until a scheduled major breaking change.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
In general, if your project intentionally duplicates enum member values, you can avoid this rule.
|
||||
17
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-duplicate-imports.mdx
generated
vendored
17
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-duplicate-imports.mdx
generated
vendored
|
|
@ -1,17 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been deprecated in favour of the [`import/no-duplicates`](https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-duplicates.md) rule.
|
||||
|
||||
:::
|
||||
|
||||
<!--
|
||||
This doc file has been left on purpose because `import/no-duplicates` is
|
||||
commonly requested. This exists to help direct people to the replacement rule.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar.
|
||||
-->
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
---
|
||||
description: 'Disallow duplicate constituents of union or intersection types.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-duplicate-type-constituents** for documentation.
|
||||
|
||||
TypeScript supports types ("constituents") within union and intersection types being duplicates of each other.
|
||||
However, developers typically expect each constituent to be unique within its intersection or union.
|
||||
Duplicate values make the code overly verbose and generally reduce readability.
|
||||
|
||||
This rule disallows duplicate union or intersection constituents.
|
||||
We consider types to be duplicate if they evaluate to the same result in the type system.
|
||||
For example, given `type A = string` and `type T = string | A`, this rule would flag that `A` is the same type as `string`.
|
||||
|
||||
This rule also disallows explicitly listing `undefined` in a type union when a function parameter is marked as optional.
|
||||
Doing so is unnecessary.
|
||||
Please note that this check only applies to parameters, not properties.
|
||||
Therefore, it does not conflict with the [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes) TypeScript compiler setting.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
type T1 = 'A' | 'A';
|
||||
|
||||
type T2 = string | string | number;
|
||||
|
||||
type T3 = { a: string } & { a: string };
|
||||
|
||||
type T4 = [1, 2, 3] | [1, 2, 3];
|
||||
|
||||
type StringA = string;
|
||||
type StringB = string;
|
||||
type T5 = StringA | StringB;
|
||||
|
||||
const fn = (a?: string | undefined) => {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
type T1 = 'A' | 'B';
|
||||
|
||||
type T2 = string | number | boolean;
|
||||
|
||||
type T3 = { a: string } & { b: string };
|
||||
|
||||
type T4 = [1, 2, 3] | [1, 2, 3, 4];
|
||||
|
||||
type StringA = string;
|
||||
type NumberB = number;
|
||||
type T5 = StringA | NumberB;
|
||||
|
||||
const fn = (a?: string) => {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `ignoreIntersections`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
When set to true, duplicate checks on intersection type constituents are ignored.
|
||||
|
||||
### `ignoreUnions`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
When set to true, duplicate checks on union type constituents are ignored.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
It can sometimes be useful for the sake of documentation to include aliases for the same type.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
> In some of those cases, [branded types](https://basarat.gitbook.io/typescript/main-1/nominaltyping#using-interfaces) might be a type-safe way to represent the underlying data types.
|
||||
|
||||
## Related To
|
||||
|
||||
- [no-redundant-type-constituents](./no-redundant-type-constituents.mdx)
|
||||
64
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-dynamic-delete.mdx
generated
vendored
64
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-dynamic-delete.mdx
generated
vendored
|
|
@ -1,64 +0,0 @@
|
|||
---
|
||||
description: 'Disallow using the `delete` operator on computed key expressions.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-dynamic-delete** for documentation.
|
||||
|
||||
Deleting dynamically computed keys can be dangerous and in some cases not well optimized.
|
||||
Using the `delete` operator on keys that aren't runtime constants could be a sign that you're using the wrong data structures.
|
||||
Consider using a `Map` or `Set` if you’re using an object as a key-value collection.
|
||||
|
||||
Dynamically adding and removing keys from objects can cause occasional edge case bugs. For example, some objects use "hidden properties" (such as `__data`) for private storage, and deleting them can break the object's internal state. Furthermore, [`delete`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) cannot remove inherited properties or non-configurable properties. This makes it interact badly with anything more complicated than a plain object:
|
||||
|
||||
- The [`length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) of an array is non-configurable, and deleting it is a runtime error.
|
||||
- You can't remove properties on the prototype of an object, such as deleting methods from class instances.
|
||||
- Sometimes, `delete` only removes the own property, leaving the inherited property intact. For example, deleting the [`name`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property of a function only removes the own property, but there's also a `Function.prototype.name` property that remains.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// Dynamic, difficult-to-reason-about lookups
|
||||
const name = 'name';
|
||||
delete container[name];
|
||||
delete container[name.toUpperCase()];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
const container: { [i: string]: number } = {
|
||||
/* ... */
|
||||
};
|
||||
|
||||
// Constant runtime lookups by string index
|
||||
delete container.aaa;
|
||||
|
||||
// Constants that must be accessed by []
|
||||
delete container[7];
|
||||
delete container[-1];
|
||||
|
||||
// All strings are allowed, to be compatible with the noPropertyAccessFromIndexSignature
|
||||
// TS compiler option
|
||||
delete container['aaa'];
|
||||
delete container['Infinity'];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
When you know your keys are safe to delete, this rule can be unnecessary.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
Do not consider this rule as performance advice before profiling your code's bottlenecks.
|
||||
Even repeated minor performance slowdowns likely do not significantly affect your application's general perceived speed.
|
||||
94
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-empty-function.mdx
generated
vendored
94
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-empty-function.mdx
generated
vendored
|
|
@ -1,94 +0,0 @@
|
|||
---
|
||||
description: 'Disallow empty functions.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-empty-function** for documentation.
|
||||
|
||||
It adds support for handling TypeScript specific code that would otherwise trigger the rule.
|
||||
|
||||
One example of valid TypeScript specific code that would otherwise trigger the `no-empty-function` rule is the use of [parameter properties](https://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties) in constructor functions.
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
type AdditionalAllowOptionEntries =
|
||||
| 'private-constructors'
|
||||
| 'protected-constructors'
|
||||
| 'decoratedFunctions'
|
||||
| 'overrideMethods';
|
||||
|
||||
type AllowOptionEntries =
|
||||
| BaseNoEmptyFunctionAllowOptionEntries
|
||||
| AdditionalAllowOptionEntries;
|
||||
|
||||
interface Options extends BaseNoEmptyFunctionOptions {
|
||||
allow?: Array<AllowOptionEntries>;
|
||||
}
|
||||
const defaultOptions: Options = {
|
||||
...baseNoEmptyFunctionDefaultOptions,
|
||||
allow: [],
|
||||
};
|
||||
```
|
||||
|
||||
### allow: `private-constructors`
|
||||
|
||||
Examples of correct code for the `{ "allow": ["private-constructors"] }` option:
|
||||
|
||||
```ts option='{ "allow": ["private-constructors"] }' showPlaygroundButton
|
||||
class Foo {
|
||||
private constructor() {}
|
||||
}
|
||||
```
|
||||
|
||||
### allow: `protected-constructors`
|
||||
|
||||
Examples of correct code for the `{ "allow": ["protected-constructors"] }` option:
|
||||
|
||||
```ts option='{ "allow": ["protected-constructors"] }' showPlaygroundButton
|
||||
class Foo {
|
||||
protected constructor() {}
|
||||
}
|
||||
```
|
||||
|
||||
### allow: `decoratedFunctions`
|
||||
|
||||
Examples of correct code for the `{ "allow": ["decoratedFunctions"] }` option:
|
||||
|
||||
```ts option='{ "allow": ["decoratedFunctions"] }' showPlaygroundButton
|
||||
class Foo {
|
||||
@decorator()
|
||||
foo() {}
|
||||
}
|
||||
```
|
||||
|
||||
### allow: `overrideMethods`
|
||||
|
||||
Examples of correct code for the `{ "allow": ["overrideMethods"] }` option:
|
||||
|
||||
```ts option='{ "allow": ["overrideMethods"] }' showPlaygroundButton
|
||||
abstract class Base {
|
||||
protected greet(): void {
|
||||
console.log('Hello!');
|
||||
}
|
||||
}
|
||||
|
||||
class Foo extends Base {
|
||||
protected override greet(): void {}
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you are working with external APIs that require functions even if they do nothing, then you may want to avoid this rule.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
Test code often violates this rule as well.
|
||||
If your testing setup doesn't support "mock" or "spy" functions such as [`jest.fn()`](https://jestjs.io/docs/mock-functions), [`sinon.spy()`](https://sinonjs.org/releases/latest/spies), or [`vi.fn()`](https://vitest.dev/guide/mocking.html), you may wish to disable this rule in test files.
|
||||
Again, if those cases aren't extremely common, you might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule in test files.
|
||||
75
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-empty-interface.mdx
generated
vendored
75
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-empty-interface.mdx
generated
vendored
|
|
@ -1,75 +0,0 @@
|
|||
---
|
||||
description: 'Disallow the declaration of empty interfaces.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-empty-interface** for documentation.
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been deprecated in favour of the more comprehensive [`@typescript-eslint/no-empty-object-type`](./no-empty-object-type.mdx) rule.
|
||||
|
||||
:::
|
||||
|
||||
An empty interface in TypeScript does very little: any non-nullable value is assignable to `{}`.
|
||||
Using an empty interface is often a sign of programmer error, such as misunderstanding the concept of `{}` or forgetting to fill in fields.
|
||||
|
||||
This rule aims to ensure that only meaningful interfaces are declared in the code.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// an empty interface
|
||||
interface Foo {}
|
||||
|
||||
// an interface with only one supertype (Bar === Foo)
|
||||
interface Bar extends Foo {}
|
||||
|
||||
// an interface with an empty list of supertypes
|
||||
interface Baz {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
// an interface with any number of members
|
||||
interface Foo {
|
||||
name: string;
|
||||
}
|
||||
|
||||
// same as above
|
||||
interface Bar {
|
||||
age: number;
|
||||
}
|
||||
|
||||
// an interface with more than one supertype
|
||||
// in this case the interface can be used as a replacement of an intersection type.
|
||||
interface Baz extends Foo, Bar {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allowSingleExtends`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
`allowSingleExtends: true` will silence warnings about extending a single interface without adding additional members.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't care about having empty/meaningless interfaces, then you will not need this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`no-empty-object-type`](./no-empty-object-type.mdx)
|
||||
150
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-empty-object-type.mdx
generated
vendored
150
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-empty-object-type.mdx
generated
vendored
|
|
@ -1,150 +0,0 @@
|
|||
---
|
||||
description: 'Disallow accidentally using the "empty object" type.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-empty-object-type** for documentation.
|
||||
|
||||
The `{}`, or "empty object" type in TypeScript is a common source of confusion for developers unfamiliar with TypeScript's structural typing.
|
||||
`{}` represents any _non-nullish value_, including literals like `0` and `""`:
|
||||
|
||||
```ts
|
||||
let anyNonNullishValue: {} = 'Intentionally allowed by TypeScript.';
|
||||
```
|
||||
|
||||
Often, developers writing `{}` actually mean either:
|
||||
|
||||
- `object`: representing any _object_ value
|
||||
- `unknown`: representing any value at all, including `null` and `undefined`
|
||||
|
||||
In other words, the "empty object" type `{}` really means _"any value that is defined"_.
|
||||
That includes arrays, class instances, functions, and primitives such as `string` and `symbol`.
|
||||
|
||||
To avoid confusion around the `{}` type allowing any _non-nullish value_, this rule bans usage of the `{}` type.
|
||||
That includes interfaces and object type aliases with no fields.
|
||||
|
||||
:::tip
|
||||
If you do have a use case for an API allowing `{}`, you can always configure the [rule's options](#options), use an [ESLint disable comment](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1), or [disable the rule in your ESLint config](https://eslint.org/docs/latest/use/configure/rules#using-configuration-files-1).
|
||||
:::
|
||||
|
||||
Note that this rule does not report on:
|
||||
|
||||
- `{}` as a type constituent in an intersection type (e.g. types like TypeScript's built-in `type NonNullable<T> = T & {}`), as this can be useful in type system operations.
|
||||
- Interfaces that extend from multiple other interfaces.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
let anyObject: {};
|
||||
let anyValue: {};
|
||||
|
||||
interface AnyObjectA {}
|
||||
interface AnyValueA {}
|
||||
|
||||
type AnyObjectB = {};
|
||||
type AnyValueB = {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
let anyObject: object;
|
||||
let anyValue: unknown;
|
||||
|
||||
type AnyObjectA = object;
|
||||
type AnyValueA = unknown;
|
||||
|
||||
type AnyObjectB = object;
|
||||
type AnyValueB = unknown;
|
||||
|
||||
let objectWith: { property: boolean };
|
||||
|
||||
interface InterfaceWith {
|
||||
property: boolean;
|
||||
}
|
||||
|
||||
type TypeWith = { property: boolean };
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
By default, this rule flags both interfaces and object types.
|
||||
|
||||
### `allowInterfaces`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Allowed values are:
|
||||
|
||||
- `'always'`: to always allow interfaces with no fields
|
||||
- `'never'` _(default)_: to never allow interfaces with no fields
|
||||
- `'with-single-extends'`: to allow empty interfaces that `extend` from a single base interface
|
||||
|
||||
Examples of **correct** code for this rule with `{ allowInterfaces: 'with-single-extends' }`:
|
||||
|
||||
```ts option='{ "allowInterfaces": "with-single-extends" }' showPlaygroundButton
|
||||
interface Base {
|
||||
value: boolean;
|
||||
}
|
||||
|
||||
interface Derived extends Base {}
|
||||
```
|
||||
|
||||
### `allowObjectTypes`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Allowed values are:
|
||||
|
||||
- `'always'`: to always allow object type literals with no fields
|
||||
- `'never'` _(default)_: to never allow object type literals with no fields
|
||||
|
||||
### `allowWithName`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This can be useful if your existing code style includes a pattern of declaring empty types with `{}` instead of `object`.
|
||||
|
||||
Examples of code for this rule with `{ allowWithName: 'Props$' }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowWithName": "Props$" }' showPlaygroundButton
|
||||
interface InterfaceValue {}
|
||||
|
||||
type TypeValue = {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowWithName": "Props$" }' showPlaygroundButton
|
||||
interface InterfaceProps {}
|
||||
|
||||
type TypeProps = {};
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your code commonly needs to represent the _"any non-nullish value"_ type, this rule may not be for you.
|
||||
Projects that extensively use type operations such as conditional types and mapped types oftentimes benefit from disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [Enhancement: [ban-types] Split the {} ban into a separate, better-phrased rule](https://github.com/typescript-eslint/typescript-eslint/issues/8700)
|
||||
- [The Empty Object Type in TypeScript](https://www.totaltypescript.com/the-empty-object-type-in-typescript)
|
||||
177
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-explicit-any.mdx
generated
vendored
177
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-explicit-any.mdx
generated
vendored
|
|
@ -1,177 +0,0 @@
|
|||
---
|
||||
description: 'Disallow the `any` type.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-explicit-any** for documentation.
|
||||
|
||||
The `any` type in TypeScript is a dangerous "escape hatch" from the type system.
|
||||
Using `any` disables many type checking rules and is generally best used only as a last resort or when prototyping code.
|
||||
This rule reports on explicit uses of the `any` keyword as a type annotation.
|
||||
|
||||
Preferable alternatives to `any` include:
|
||||
|
||||
- If the type is known, describing it in an `interface` or `type`
|
||||
- If the type is not known, using the safer `unknown` type
|
||||
|
||||
> TypeScript's `--noImplicitAny` compiler option prevents an implied `any`, but doesn't prevent `any` from being explicitly used the way this rule does.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
const age: any = 'seventeen';
|
||||
```
|
||||
|
||||
```ts
|
||||
const ages: any[] = ['seventeen'];
|
||||
```
|
||||
|
||||
```ts
|
||||
const ages: Array<any> = ['seventeen'];
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): any {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): any[] {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): Array<any> {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): Array<Array<any>> {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(param: Array<any>): string {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(param: Array<any>): Array<any> {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
const age: number = 17;
|
||||
```
|
||||
|
||||
```ts
|
||||
const ages: number[] = [17];
|
||||
```
|
||||
|
||||
```ts
|
||||
const ages: Array<number> = [17];
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): string {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): string[] {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): Array<string> {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(): Array<Array<string>> {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(param: Array<string>): string {}
|
||||
```
|
||||
|
||||
```ts
|
||||
function greet(param: Array<string>): Array<string> {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `fixToUnknown`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
By default, this rule will not provide automatic ESLint _fixes_: only opt-in _suggestions_.
|
||||
Switching types to `unknown` is safer but is likely to cause additional type errors.
|
||||
|
||||
Enabling `{ "fixToUnknown": true }` gives the rule an auto-fixer to replace `: any` with `: unknown`.
|
||||
|
||||
### `ignoreRestArgs`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
The examples below are **incorrect** when `{ignoreRestArgs: false}`, but **correct** when `{ignoreRestArgs: true}`.
|
||||
|
||||
```ts option='{ "ignoreRestArgs": false }' showPlaygroundButton
|
||||
function foo1(...args: any[]): void {}
|
||||
function foo2(...args: readonly any[]): void {}
|
||||
function foo3(...args: Array<any>): void {}
|
||||
function foo4(...args: ReadonlyArray<any>): void {}
|
||||
|
||||
declare function bar(...args: any[]): void;
|
||||
|
||||
const baz = (...args: any[]) => {};
|
||||
const qux = function (...args: any[]) {};
|
||||
|
||||
type Quux = (...args: any[]) => void;
|
||||
type Quuz = new (...args: any[]) => void;
|
||||
|
||||
interface Grault {
|
||||
(...args: any[]): void;
|
||||
}
|
||||
interface Corge {
|
||||
new (...args: any[]): void;
|
||||
}
|
||||
interface Garply {
|
||||
f(...args: any[]): void;
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
`any` is always a dangerous escape hatch.
|
||||
Whenever possible, it is always safer to avoid it.
|
||||
TypeScript's `unknown` is almost always preferable to `any`.
|
||||
|
||||
However, there are occasional situations where it can be necessary to use `any`.
|
||||
Most commonly:
|
||||
|
||||
- If your project isn't fully onboarded to TypeScript yet, `any` can be temporarily used in places where types aren't yet known or representable
|
||||
- If an external package doesn't yet have typings and you want to use `any` pending adding a `.d.ts` for it
|
||||
- You're working with particularly complex or nuanced code that can't yet be represented in the TypeScript type system
|
||||
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [Avoiding `any`s with Linting and TypeScript](/blog/avoiding-anys)
|
||||
- [`no-unsafe-argument`](./no-unsafe-argument.mdx)
|
||||
- [`no-unsafe-assignment`](./no-unsafe-assignment.mdx)
|
||||
- [`no-unsafe-call`](./no-unsafe-call.mdx)
|
||||
- [`no-unsafe-member-access`](./no-unsafe-member-access.mdx)
|
||||
- [`no-unsafe-return`](./no-unsafe-return.mdx)
|
||||
|
||||
## Further Reading
|
||||
|
||||
- TypeScript [`any` type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)
|
||||
- TypeScript's [`unknown` type](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown)
|
||||
- TypeScript [`any` type documentation](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any)
|
||||
- TypeScript [`unknown` type release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type)
|
||||
60
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extra-non-null-assertion.mdx
generated
vendored
60
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extra-non-null-assertion.mdx
generated
vendored
|
|
@ -1,60 +0,0 @@
|
|||
---
|
||||
description: 'Disallow extra non-null assertions.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-extra-non-null-assertion** for documentation.
|
||||
|
||||
The `!` non-null assertion operator in TypeScript is used to assert that a value's type does not include `null` or `undefined`.
|
||||
Using the operator any more than once on a single value does nothing.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
const foo: { bar: number } | null = null;
|
||||
const bar = foo!!!.bar;
|
||||
```
|
||||
|
||||
```ts
|
||||
function foo(bar: number | undefined) {
|
||||
const bar: number = bar!!!;
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
function foo(bar?: { n: number }) {
|
||||
return bar!?.n;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
const foo: { bar: number } | null = null;
|
||||
const bar = foo!.bar;
|
||||
```
|
||||
|
||||
```ts
|
||||
function foo(bar: number | undefined) {
|
||||
const bar: number = bar!;
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
function foo(bar?: { n: number }) {
|
||||
return bar?.n;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
{/* Intentionally Omitted: When Not To Use It */}
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extra-parens.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extra-parens.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extra-semi.md
generated
vendored
15
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extra-semi.md
generated
vendored
|
|
@ -1,15 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).
|
||||
See [#8072](https://github.com/typescript-eslint/typescript-eslint/issues/8072) and [#8074](https://github.com/typescript-eslint/typescript-eslint/issues/8074) for more information.
|
||||
|
||||
:::
|
||||
|
||||
<!-- This doc file has been left on purpose to help direct people to the stylistic plugin.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar. -->
|
||||
329
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extraneous-class.mdx
generated
vendored
329
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-extraneous-class.mdx
generated
vendored
|
|
@ -1,329 +0,0 @@
|
|||
---
|
||||
description: 'Disallow classes used as namespaces.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-extraneous-class** for documentation.
|
||||
|
||||
This rule reports when a class has no non-static members, such as for a class used exclusively as a static namespace.
|
||||
|
||||
Users who come from a [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) paradigm may wrap their utility functions in an extra class, instead of putting them at the top level of an ECMAScript module.
|
||||
Doing so is generally unnecessary in JavaScript and TypeScript projects.
|
||||
|
||||
- Wrapper classes add extra cognitive complexity to code without adding any structural improvements
|
||||
- Whatever would be put on them, such as utility functions, are already organized by virtue of being in a module.
|
||||
- As an alternative, you can `import * as ...` the module to get all of them in a single object.
|
||||
- IDEs can't provide as good suggestions for static class or namespace imported properties when you start typing property names
|
||||
- It's more difficult to statically analyze code for unused variables, etc. when they're all on the class (see: [Finding dead code (and dead types) in TypeScript](https://effectivetypescript.com/2020/10/20/tsprune)).
|
||||
|
||||
This rule also reports classes that have only a constructor and no fields.
|
||||
Those classes can generally be replaced with a standalone function.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
class StaticConstants {
|
||||
static readonly version = 42;
|
||||
|
||||
static isProduction() {
|
||||
return process.env.NODE_ENV === 'production';
|
||||
}
|
||||
}
|
||||
|
||||
class HelloWorldLogger {
|
||||
constructor() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Foo {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
export const version = 42;
|
||||
|
||||
export function isProduction() {
|
||||
return process.env.NODE_ENV === 'production';
|
||||
}
|
||||
|
||||
function logHelloWorld() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
|
||||
abstract class Foo {
|
||||
abstract prop: string;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Alternatives
|
||||
|
||||
### Individual Exports (Recommended)
|
||||
|
||||
Instead of using a static utility class we recommend you individually export the utilities from your module.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
export class Utilities {
|
||||
static util1() {
|
||||
return Utilities.util3();
|
||||
}
|
||||
|
||||
static util2() {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
static util3() {
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
export function util1() {
|
||||
return util3();
|
||||
}
|
||||
|
||||
export function util2() {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
export function util3() {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### Namespace Imports (Not Recommended)
|
||||
|
||||
If you strongly prefer to have all constructs from a module available as properties of a single object, you can `import * as` the module.
|
||||
This is known as a "namespace import".
|
||||
Namespace imports are sometimes preferable because they keep all properties nested and don't need to be changed as you start or stop using various properties from the module.
|
||||
|
||||
However, namespace imports are impacted by these downsides:
|
||||
|
||||
- They also don't play as well with tree shaking in modern bundlers
|
||||
- They require a name prefix before each property's usage
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
// utilities.ts
|
||||
export class Utilities {
|
||||
static sayHello() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
}
|
||||
|
||||
// consumers.ts
|
||||
import { Utilities } from './utilities';
|
||||
|
||||
Utilities.sayHello();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="⚠️ Namespace Imports">
|
||||
|
||||
```ts
|
||||
// utilities.ts
|
||||
export function sayHello() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
|
||||
// consumers.ts
|
||||
import * as utilities from './utilities';
|
||||
|
||||
utilities.sayHello();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Standalone Imports">
|
||||
|
||||
```ts
|
||||
// utilities.ts
|
||||
export function sayHello() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
|
||||
// consumers.ts
|
||||
import { sayHello } from './utilities';
|
||||
|
||||
sayHello();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### Notes on Mutating Variables
|
||||
|
||||
One case you need to be careful of is exporting mutable variables.
|
||||
While class properties can be mutated externally, exported variables are always constant.
|
||||
This means that importers can only ever read the first value they are assigned and cannot write to the variables.
|
||||
|
||||
Needing to write to an exported variable is very rare and is generally considered a code smell.
|
||||
If you do need it you can accomplish it using getter and setter functions:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
export class Utilities {
|
||||
static mutableCount = 1;
|
||||
|
||||
static incrementCount() {
|
||||
Utilities.mutableCount += 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
let mutableCount = 1;
|
||||
|
||||
export function getMutableCount() {
|
||||
return mutableField;
|
||||
}
|
||||
|
||||
export function incrementCount() {
|
||||
mutableField += 1;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
This rule normally bans classes that are empty (have no constructor or fields).
|
||||
The rule's options each add an exemption for a specific type of class.
|
||||
|
||||
### `allowConstructorOnly`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowConstructorOnly": true }'
|
||||
class NoFields {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowConstructorOnly": true }'
|
||||
class NoFields {
|
||||
constructor() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowEmpty`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowEmpty": true }'
|
||||
class NoFields {
|
||||
constructor() {
|
||||
console.log('Hello, world!');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowEmpty": true }'
|
||||
class NoFields {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowStaticOnly`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
:::caution
|
||||
We strongly recommend against the `allowStaticOnly` exemption.
|
||||
It works against this rule's primary purpose of discouraging classes used only for static members.
|
||||
:::
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowStaticOnly": true }'
|
||||
class EmptyClass {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowStaticOnly": true }'
|
||||
class NotEmptyClass {
|
||||
static version = 42;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowWithDecorator`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowWithDecorator": true }'
|
||||
class Constants {
|
||||
static readonly version = 42;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowWithDecorator": true }'
|
||||
@logOnRead()
|
||||
class Constants {
|
||||
static readonly version = 42;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project was set up before modern class and namespace practices, and you don't have the time to switch over, you might not be practically able to use this rule.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
282
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-floating-promises.mdx
generated
vendored
282
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-floating-promises.mdx
generated
vendored
|
|
@ -1,282 +0,0 @@
|
|||
---
|
||||
description: 'Require Promise-like statements to be handled appropriately.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-floating-promises** for documentation.
|
||||
|
||||
A "floating" Promise is one that is created without any code set up to handle any errors it might throw.
|
||||
Floating Promises can cause several issues, such as improperly sequenced operations, ignored Promise rejections, and more.
|
||||
|
||||
This rule will report Promise-valued statements that are not treated in one of the following ways:
|
||||
|
||||
- Calling its `.then()` with two arguments
|
||||
- Calling its `.catch()` with one argument
|
||||
- `await`ing it
|
||||
- `return`ing it
|
||||
- [`void`ing it](#ignorevoid)
|
||||
|
||||
This rule also reports when an Array containing Promises is created and not properly handled. The main way to resolve this is by using one of the Promise concurrency methods to create a single Promise, then handling that according to the procedure above. These methods include:
|
||||
|
||||
- `Promise.all()`
|
||||
- `Promise.allSettled()`
|
||||
- `Promise.any()`
|
||||
- `Promise.race()`
|
||||
|
||||
:::tip
|
||||
`no-floating-promises` only detects apparently unhandled Promise _statements_.
|
||||
See [`no-misused-promises`](./no-misused-promises.mdx) for detecting code that provides Promises to _logical_ locations such as if statements.
|
||||
|
||||
See [_Using promises (error handling) on MDN_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#error_handling) for a detailed writeup on Promise error-handling.
|
||||
:::
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
const promise = new Promise((resolve, reject) => resolve('value'));
|
||||
promise;
|
||||
|
||||
async function returnsPromise() {
|
||||
return 'value';
|
||||
}
|
||||
returnsPromise().then(() => {});
|
||||
|
||||
Promise.reject('value').catch();
|
||||
|
||||
Promise.reject('value').finally();
|
||||
|
||||
[1, 2, 3].map(async x => x + 1);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
const promise = new Promise((resolve, reject) => resolve('value'));
|
||||
await promise;
|
||||
|
||||
async function returnsPromise() {
|
||||
return 'value';
|
||||
}
|
||||
|
||||
void returnsPromise();
|
||||
|
||||
returnsPromise().then(
|
||||
() => {},
|
||||
() => {},
|
||||
);
|
||||
|
||||
Promise.reject('value').catch(() => {});
|
||||
|
||||
await Promise.reject('value').finally(() => {});
|
||||
|
||||
await Promise.all([1, 2, 3].map(async x => x + 1));
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `checkThenables`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
A ["Thenable"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is an object which has a `then` method, such as a `Promise`.
|
||||
Other Thenables include TypeScript's built-in `PromiseLike` interface and any custom object that happens to have a `.then()`.
|
||||
|
||||
The `checkThenables` option triggers `no-floating-promises` to also consider all values that satisfy the Thenable shape (a `.then()` method that takes two callback parameters), not just Promises.
|
||||
This can be useful if your code works with older `Promise` polyfills instead of the native `Promise` class.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{"checkThenables": true}'
|
||||
declare function createPromiseLike(): PromiseLike<string>;
|
||||
|
||||
createPromiseLike();
|
||||
|
||||
interface MyThenable {
|
||||
then(onFulfilled: () => void, onRejected: () => void): MyThenable;
|
||||
}
|
||||
|
||||
declare function createMyThenable(): MyThenable;
|
||||
|
||||
createMyThenable();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{"checkThenables": true}'
|
||||
declare function createPromiseLike(): PromiseLike<string>;
|
||||
|
||||
await createPromiseLike();
|
||||
|
||||
interface MyThenable {
|
||||
then(onFulfilled: () => void, onRejected: () => void): MyThenable;
|
||||
}
|
||||
|
||||
declare function createMyThenable(): MyThenable;
|
||||
|
||||
await createMyThenable();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `ignoreVoid`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Placing the [`void` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) in front of a Promise can be a convenient way to explicitly mark that Promise as intentionally not awaited.
|
||||
|
||||
:::warning
|
||||
Voiding a Promise doesn't handle it or change the runtime behavior.
|
||||
The outcome is just ignored, like disabling the rule with an [ESLint disable comment](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1).
|
||||
Such Promise rejections will still be unhandled.
|
||||
:::
|
||||
|
||||
Examples of **correct** code for this rule with `{ ignoreVoid: true }`:
|
||||
|
||||
```ts option='{ "ignoreVoid": true }' showPlaygroundButton
|
||||
async function returnsPromise() {
|
||||
return 'value';
|
||||
}
|
||||
void returnsPromise();
|
||||
|
||||
void Promise.reject('value');
|
||||
```
|
||||
|
||||
When this option is set to `true`, if you are using `no-void`, you should turn on the [`allowAsStatement`](https://eslint.org/docs/rules/no-void#allowasstatement) option.
|
||||
|
||||
### `ignoreIIFE`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of **correct** code for this rule with `{ ignoreIIFE: true }`:
|
||||
|
||||
{/* prettier-ignore */}
|
||||
```ts option='{ "ignoreIIFE": true }' showPlaygroundButton
|
||||
await (async function () {
|
||||
await res(1);
|
||||
})();
|
||||
|
||||
(async function () {
|
||||
await res(1);
|
||||
})();
|
||||
```
|
||||
|
||||
### `allowForKnownSafePromises`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
For example, you may need to do this in the case of libraries whose APIs return Promises whose rejections are safely handled by the library.
|
||||
|
||||
This option takes the shared [`TypeOrValueSpecifier` format](/packages/type-utils/type-or-value-specifier).
|
||||
|
||||
Examples of code for this rule with:
|
||||
|
||||
```json
|
||||
{
|
||||
"allowForKnownSafePromises": [
|
||||
{ "from": "file", "name": "SafePromise" },
|
||||
{ "from": "lib", "name": "PromiseLike" },
|
||||
{ "from": "package", "name": "Bar", "package": "bar-lib" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{"allowForKnownSafePromises":[{"from":"file","name":"SafePromise"},{"from":"lib","name":"PromiseLike"},{"from":"package","name":"Bar","package":"bar-lib"}]}'
|
||||
let promise: Promise<number> = Promise.resolve(2);
|
||||
promise;
|
||||
|
||||
function returnsPromise(): Promise<number> {
|
||||
return Promise.resolve(42);
|
||||
}
|
||||
|
||||
returnsPromise();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{"allowForKnownSafePromises":[{"from":"file","name":"SafePromise"},{"from":"lib","name":"PromiseLike"},{"from":"package","name":"Bar","package":"bar-lib"}]}'
|
||||
// promises can be marked as safe by using branded types
|
||||
type SafePromise = Promise<number> & { __linterBrands?: string };
|
||||
|
||||
let promise: SafePromise = Promise.resolve(2);
|
||||
promise;
|
||||
|
||||
function returnsSafePromise(): SafePromise {
|
||||
return Promise.resolve(42);
|
||||
}
|
||||
|
||||
returnsSafePromise();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowForKnownSafeCalls`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
For example, you may need to do this in the case of libraries whose APIs may be called without handling the resultant Promises.
|
||||
|
||||
This option takes the shared [`TypeOrValueSpecifier` format](/packages/type-utils/type-or-value-specifier).
|
||||
|
||||
Examples of code for this rule with:
|
||||
|
||||
```json
|
||||
{
|
||||
"allowForKnownSafeCalls": [
|
||||
{ "from": "file", "name": "safe", "path": "input.ts" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{"allowForKnownSafeCalls":[{"from":"file","name":"safe","path":"input.ts"}]}'
|
||||
declare function unsafe(...args: unknown[]): Promise<void>;
|
||||
|
||||
unsafe('...', () => {});
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{"allowForKnownSafeCalls":[{"from":"file","name":"safe","path":"input.ts"}]}' skipValidation
|
||||
declare function safe(...args: unknown[]): Promise<void>;
|
||||
|
||||
safe('...', () => {});
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
This rule can be difficult to enable on large existing projects that set up many floating Promises.
|
||||
Alternately, if you're not worried about crashes from floating or misused Promises -such as if you have global unhandled Promise handlers registered- then in some cases it may be safe to not use this rule.
|
||||
You might consider using `void`s and/or [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`no-misused-promises`](./no-misused-promises.mdx)
|
||||
|
||||
## Further Reading
|
||||
|
||||
- ["Using Promises" MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). Note especially the sections on [Promise rejection events](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events) and [Composition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#composition).
|
||||
67
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-for-in-array.mdx
generated
vendored
67
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-for-in-array.mdx
generated
vendored
|
|
@ -1,67 +0,0 @@
|
|||
---
|
||||
description: 'Disallow iterating over an array with a for-in loop.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-for-in-array** for documentation.
|
||||
|
||||
A for-in loop (`for (const i in o)`) iterates over the properties of an Object.
|
||||
While it is legal to use for-in loops with array values, it is not common. There are several potential bugs with this:
|
||||
|
||||
1. It iterates over all enumerable properties, including non-index ones and the entire prototype chain. For example, [`RegExp.prototype.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) returns an array with additional properties, and `for-in` will iterate over them. Some libraries or even your own code may add additional methods to `Array.prototype` (either as polyfill or as custom methods), and if not done properly, they may be iterated over as well.
|
||||
2. It skips holes in the array. While sparse arrays are rare and advised against, they are still possible and your code should be able to handle them.
|
||||
3. The "index" is returned as a string, not a number. This can be caught by TypeScript, but can still lead to subtle bugs.
|
||||
|
||||
You may have confused for-in with for-of, which iterates over the elements of the array. If you actually need the index, use a regular `for` loop or the `forEach` method.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
declare const array: string[];
|
||||
|
||||
for (const i in array) {
|
||||
console.log(array[i]);
|
||||
}
|
||||
|
||||
for (const i in array) {
|
||||
console.log(i, array[i]);
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
declare const array: string[];
|
||||
|
||||
for (const value of array) {
|
||||
console.log(value);
|
||||
}
|
||||
|
||||
for (let i = 0; i < array.length; i += 1) {
|
||||
console.log(i, array[i]);
|
||||
}
|
||||
|
||||
array.forEach((value, i) => {
|
||||
console.log(i, value);
|
||||
});
|
||||
|
||||
for (const [i, value] of array.entries()) {
|
||||
console.log(i, value);
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project is a rare one that intentionally loops over string indices of arrays, you can turn off this rule.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
106
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-implied-eval.mdx
generated
vendored
106
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-implied-eval.mdx
generated
vendored
|
|
@ -1,106 +0,0 @@
|
|||
---
|
||||
description: 'Disallow the use of `eval()`-like functions.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-implied-eval** for documentation.
|
||||
|
||||
It uses type information to determine which values are `eval()`-like functions.
|
||||
|
||||
It's considered a good practice to avoid using `eval()`. There are security and performance implications involved with doing so, which is why many linters recommend disallowing `eval()`. However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.
|
||||
|
||||
The first is using `setTimeout()`, `setInterval()`, `setImmediate` or `execScript()` (Internet Explorer only), all of which can accept a string of code as their first argument
|
||||
|
||||
```ts
|
||||
setTimeout('alert(`Hi!`);', 100);
|
||||
```
|
||||
|
||||
or using `new Function()`
|
||||
|
||||
```ts
|
||||
const fn = new Function('a', 'b', 'return a + b');
|
||||
```
|
||||
|
||||
This is considered an implied `eval()` because a string of code is
|
||||
passed in to be interpreted. The same can be done with `setInterval()`, `setImmediate()` and `execScript()`. All interpret the JavaScript code in the global scope.
|
||||
|
||||
The best practice is to avoid using `new Function()` or `execScript()` and always use a function for the first argument of `setTimeout()`, `setInterval()` and `setImmediate()`.
|
||||
|
||||
## Examples
|
||||
|
||||
This rule aims to eliminate implied `eval()` through the use of `new Function()`, `setTimeout()`, `setInterval()`, `setImmediate()` or `execScript()`.
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
setTimeout('alert(`Hi!`);', 100);
|
||||
|
||||
setInterval('alert(`Hi!`);', 100);
|
||||
|
||||
setImmediate('alert(`Hi!`)');
|
||||
|
||||
execScript('alert(`Hi!`)');
|
||||
|
||||
window.setTimeout('count = 5', 10);
|
||||
|
||||
window.setInterval('foo = bar', 10);
|
||||
|
||||
const fn = '() = {}';
|
||||
setTimeout(fn, 100);
|
||||
|
||||
const fn = () => {
|
||||
return 'x = 10';
|
||||
};
|
||||
setTimeout(fn(), 100);
|
||||
|
||||
const fn = new Function('a', 'b', 'return a + b');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
setTimeout(function () {
|
||||
alert('Hi!');
|
||||
}, 100);
|
||||
|
||||
setInterval(function () {
|
||||
alert('Hi!');
|
||||
}, 100);
|
||||
|
||||
setImmediate(function () {
|
||||
alert('Hi!');
|
||||
});
|
||||
|
||||
execScript(function () {
|
||||
alert('Hi!');
|
||||
});
|
||||
|
||||
const fn = () => {};
|
||||
setTimeout(fn, 100);
|
||||
|
||||
const foo = {
|
||||
fn: function () {},
|
||||
};
|
||||
setTimeout(foo.fn, 100);
|
||||
setTimeout(foo.fn.bind(this), 100);
|
||||
|
||||
class Foo {
|
||||
static fn = () => {};
|
||||
}
|
||||
|
||||
setTimeout(Foo.fn, 100);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project is a rare one that needs to allow `new Function()` or `setTimeout()`, `setInterval()`, `setImmediate()` and `execScript()` with string arguments, then you can disable this rule.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
80
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-import-type-side-effects.mdx
generated
vendored
80
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-import-type-side-effects.mdx
generated
vendored
|
|
@ -1,80 +0,0 @@
|
|||
---
|
||||
description: 'Enforce the use of top-level import type qualifier when an import only has specifiers with inline type qualifiers.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-import-type-side-effects** for documentation.
|
||||
|
||||
The [`--verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig#verbatimModuleSyntax) compiler option causes TypeScript to do simple and predictable transpilation on import declarations.
|
||||
Namely, it completely removes import declarations with a top-level `type` qualifier, and it removes any import specifiers with an inline `type` qualifier.
|
||||
|
||||
The latter behavior does have one potentially surprising effect in that in certain cases TS can leave behind a "side effect" import at runtime:
|
||||
|
||||
```ts
|
||||
import { type A, type B } from 'mod';
|
||||
|
||||
// is transpiled to
|
||||
|
||||
import {} from 'mod';
|
||||
// which is the same as
|
||||
import 'mod';
|
||||
```
|
||||
|
||||
For the rare case of needing to import for side effects, this may be desirable - but for most cases you will not want to leave behind an unnecessary side effect import.
|
||||
|
||||
## Examples
|
||||
|
||||
This rule enforces that you use a top-level `type` qualifier for imports when it only imports specifiers with an inline `type` qualifier
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
import { type A } from 'mod';
|
||||
import { type A as AA } from 'mod';
|
||||
import { type A, type B } from 'mod';
|
||||
import { type A as AA, type B as BB } from 'mod';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
import type { A } from 'mod';
|
||||
import type { A as AA } from 'mod';
|
||||
import type { A, B } from 'mod';
|
||||
import type { A as AA, B as BB } from 'mod';
|
||||
|
||||
import T from 'mod';
|
||||
import type T from 'mod';
|
||||
|
||||
import * as T from 'mod';
|
||||
import type * as T from 'mod';
|
||||
|
||||
import { T } from 'mod';
|
||||
import type { T } from 'mod';
|
||||
import { T, U } from 'mod';
|
||||
import type { T, U } from 'mod';
|
||||
import { type T, U } from 'mod';
|
||||
import { T, type U } from 'mod';
|
||||
|
||||
import type T, { U } from 'mod';
|
||||
import T, { type U } from 'mod';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you're not using TypeScript 5.0's `verbatimModuleSyntax` option and your project is built with a bundler that manages import side effects for you, this rule may not be as useful for you.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`consistent-type-imports`](./consistent-type-imports.mdx)
|
||||
- [`import/consistent-type-specifier-style`](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/consistent-type-specifier-style.md)
|
||||
- [`import/no-duplicates` with `{"prefer-inline": true}`](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-duplicates.md#inline-type-imports)
|
||||
113
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-inferrable-types.mdx
generated
vendored
113
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-inferrable-types.mdx
generated
vendored
|
|
@ -1,113 +0,0 @@
|
|||
---
|
||||
description: 'Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-inferrable-types** for documentation.
|
||||
|
||||
TypeScript is able to infer the types of parameters, properties, and variables from their default or initial values.
|
||||
There is no need to use an explicit `:` type annotation on one of those constructs initialized to a boolean, number, or string.
|
||||
Doing so adds unnecessary verbosity to code -making it harder to read- and in some cases can prevent TypeScript from inferring a more specific literal type (e.g. `10`) instead of the more general primitive type (e.g. `number`)
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
const a: bigint = 10n;
|
||||
const a: bigint = BigInt(10);
|
||||
const a: boolean = !0;
|
||||
const a: boolean = Boolean(null);
|
||||
const a: boolean = true;
|
||||
const a: null = null;
|
||||
const a: number = 10;
|
||||
const a: number = Infinity;
|
||||
const a: number = NaN;
|
||||
const a: number = Number('1');
|
||||
const a: RegExp = /a/;
|
||||
const a: RegExp = new RegExp('a');
|
||||
const a: string = `str`;
|
||||
const a: string = String(1);
|
||||
const a: symbol = Symbol('a');
|
||||
const a: undefined = undefined;
|
||||
const a: undefined = void someValue;
|
||||
|
||||
class Foo {
|
||||
prop: number = 5;
|
||||
}
|
||||
|
||||
function fn(a: number = 5, b: boolean = true) {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
const a = 10n;
|
||||
const a = BigInt(10);
|
||||
const a = !0;
|
||||
const a = Boolean(null);
|
||||
const a = true;
|
||||
const a = null;
|
||||
const a = 10;
|
||||
const a = Infinity;
|
||||
const a = NaN;
|
||||
const a = Number('1');
|
||||
const a = /a/;
|
||||
const a = new RegExp('a');
|
||||
const a = `str`;
|
||||
const a = String(1);
|
||||
const a = Symbol('a');
|
||||
const a = undefined;
|
||||
const a = void someValue;
|
||||
|
||||
class Foo {
|
||||
prop = 5;
|
||||
}
|
||||
|
||||
function fn(a = 5, b = true) {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `ignoreParameters`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
When set to true, the following pattern is considered valid:
|
||||
|
||||
```ts option='{ "ignoreParameters": true }' showPlaygroundButton
|
||||
function foo(a: number = 5, b: boolean = true) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### `ignoreProperties`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
When set to true, the following pattern is considered valid:
|
||||
|
||||
```ts option='{ "ignoreProperties": true }' showPlaygroundButton
|
||||
class Foo {
|
||||
prop: number = 5;
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you strongly prefer to have explicit types regardless of whether they can be inferred, this rule may not be for you.
|
||||
|
||||
If you use the `--isolatedDeclarations` compiler option, this rule is incompatible.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [TypeScript Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html)
|
||||
16
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-invalid-this.mdx
generated
vendored
16
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-invalid-this.mdx
generated
vendored
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
description: 'Disallow `this` keywords outside of classes or class-like objects.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-invalid-this** for documentation.
|
||||
|
||||
import TypeScriptOverlap from '@site/src/components/TypeScriptOverlap';
|
||||
|
||||
<TypeScriptOverlap strict />
|
||||
|
||||
It adds support for TypeScript's `this` parameters.
|
||||
119
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-invalid-void-type.mdx
generated
vendored
119
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-invalid-void-type.mdx
generated
vendored
|
|
@ -1,119 +0,0 @@
|
|||
---
|
||||
description: 'Disallow `void` type outside of generic or return types.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-invalid-void-type** for documentation.
|
||||
|
||||
`void` in TypeScript refers to a function return that is meant to be ignored.
|
||||
Attempting to use a `void` type outside of a return type or generic type argument is often a sign of programmer error.
|
||||
`void` can also be misleading for other developers even if used correctly.
|
||||
|
||||
> The `void` type means cannot be mixed with any other types, other than `never`, which accepts all types.
|
||||
> If you think you need this then you probably want the `undefined` type instead.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
type PossibleValues = string | number | void;
|
||||
type MorePossibleValues = string | ((number & any) | (string | void));
|
||||
|
||||
function logSomething(thing: void) {}
|
||||
function printArg<T = void>(arg: T) {}
|
||||
|
||||
logAndReturn<void>(undefined);
|
||||
|
||||
interface Interface {
|
||||
lambda: () => void;
|
||||
prop: void;
|
||||
}
|
||||
|
||||
class MyClass {
|
||||
private readonly propName: void;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
type NoOp = () => void;
|
||||
|
||||
function noop(): void {}
|
||||
|
||||
let trulyUndefined = void 0;
|
||||
|
||||
async function promiseMeSomething(): Promise<void> {}
|
||||
|
||||
type stillVoid = void | never;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allowInGenericTypeArguments`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Alternatively, you can provide an array of strings which allowlist which types may accept `void` as a generic type parameter.
|
||||
|
||||
Any types considered valid by this option will be considered valid as part of a union type with `void`.
|
||||
|
||||
This option is `true` by default.
|
||||
|
||||
The following patterns are considered warnings with `{ allowInGenericTypeArguments: false }`:
|
||||
|
||||
```ts option='{ "allowInGenericTypeArguments": false }' showPlaygroundButton
|
||||
logAndReturn<void>(undefined);
|
||||
|
||||
let voidPromise: Promise<void> = new Promise<void>(() => {});
|
||||
let voidMap: Map<string, void> = new Map<string, void>();
|
||||
```
|
||||
|
||||
The following patterns are considered warnings with `{ allowInGenericTypeArguments: ['Ex.Mx.Tx'] }`:
|
||||
|
||||
```ts option='{ "allowInGenericTypeArguments": ["Ex.Mx.Tx"] }' showPlaygroundButton
|
||||
logAndReturn<void>(undefined);
|
||||
|
||||
type NotAllowedVoid1 = Mx.Tx<void>;
|
||||
type NotAllowedVoid2 = Tx<void>;
|
||||
type NotAllowedVoid3 = Promise<void>;
|
||||
```
|
||||
|
||||
The following patterns are not considered warnings with `{ allowInGenericTypeArguments: ['Ex.Mx.Tx'] }`:
|
||||
|
||||
```ts option='{ "allowInGenericTypeArguments": ["Ex.Mx.Tx"] }' showPlaygroundButton
|
||||
type AllowedVoid = Ex.Mx.Tx<void>;
|
||||
type AllowedVoidUnion = void | Ex.Mx.Tx<void>;
|
||||
```
|
||||
|
||||
### `allowAsThisParameter`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
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).
|
||||
|
||||
This option is `false` by default.
|
||||
|
||||
The following patterns are considered warnings with `{ allowAsThisParameter: false }` but valid with `{ allowAsThisParameter: true }`:
|
||||
|
||||
```ts option='{ "allowAsThisParameter": false }' showPlaygroundButton
|
||||
function doThing(this: void) {}
|
||||
class Example {
|
||||
static helper(this: void) {}
|
||||
callback(this: void) {}
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't care about if `void` is used with other types, or in invalid places, then you don't need this rule.
|
||||
12
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-loop-func.mdx
generated
vendored
12
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-loop-func.mdx
generated
vendored
|
|
@ -1,12 +0,0 @@
|
|||
---
|
||||
description: 'Disallow function declarations that contain unsafe references inside loop statements.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-loop-func** for documentation.
|
||||
|
||||
It adds support for TypeScript types.
|
||||
17
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-loss-of-precision.mdx
generated
vendored
17
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-loss-of-precision.mdx
generated
vendored
|
|
@ -1,17 +0,0 @@
|
|||
---
|
||||
description: 'Disallow literal numbers that lose precision.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-loss-of-precision** for documentation.
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been deprecated because the base [`eslint/no-loss-of-precision`](https://eslint.org/docs/rules/no-loss-of-precision) rule added support for [numeric separators](https://github.com/tc39/proposal-numeric-separator).
|
||||
There is no longer any need to use this extension rule.
|
||||
|
||||
:::
|
||||
131
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-magic-numbers.mdx
generated
vendored
131
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-magic-numbers.mdx
generated
vendored
|
|
@ -1,131 +0,0 @@
|
|||
---
|
||||
description: 'Disallow magic numbers.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-magic-numbers** for documentation.
|
||||
|
||||
It adds support for:
|
||||
|
||||
- numeric literal types (`type T = 1`),
|
||||
- `enum` members (`enum Foo { bar = 1 }`),
|
||||
- `readonly` class properties (`class Foo { readonly bar = 1 }`).
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
interface Options extends BaseNoMagicNumbersOptions {
|
||||
ignoreEnums?: boolean;
|
||||
ignoreNumericLiteralTypes?: boolean;
|
||||
ignoreReadonlyClassProperties?: boolean;
|
||||
ignoreTypeIndexes?: boolean;
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
...baseNoMagicNumbersDefaultOptions,
|
||||
ignoreEnums: false,
|
||||
ignoreNumericLiteralTypes: false,
|
||||
ignoreReadonlyClassProperties: false,
|
||||
ignoreTypeIndexes: false,
|
||||
};
|
||||
```
|
||||
|
||||
### `ignoreEnums`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Whether enums used in TypeScript are considered okay. `false` by default.
|
||||
|
||||
Examples of **incorrect** code for the `{ "ignoreEnums": false }` option:
|
||||
|
||||
```ts option='{ "ignoreEnums": false }' showPlaygroundButton
|
||||
enum foo {
|
||||
SECOND = 1000,
|
||||
}
|
||||
```
|
||||
|
||||
Examples of **correct** code for the `{ "ignoreEnums": true }` option:
|
||||
|
||||
```ts option='{ "ignoreEnums": true }' showPlaygroundButton
|
||||
enum foo {
|
||||
SECOND = 1000,
|
||||
}
|
||||
```
|
||||
|
||||
### `ignoreNumericLiteralTypes`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Whether numbers used in TypeScript numeric literal types are considered okay. `false` by default.
|
||||
|
||||
Examples of **incorrect** code for the `{ "ignoreNumericLiteralTypes": false }` option:
|
||||
|
||||
```ts option='{ "ignoreNumericLiteralTypes": false }' showPlaygroundButton
|
||||
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
|
||||
```
|
||||
|
||||
Examples of **correct** code for the `{ "ignoreNumericLiteralTypes": true }` option:
|
||||
|
||||
```ts option='{ "ignoreNumericLiteralTypes": true }' showPlaygroundButton
|
||||
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
|
||||
```
|
||||
|
||||
### `ignoreReadonlyClassProperties`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Whether `readonly` class properties are considered okay.
|
||||
|
||||
Examples of **incorrect** code for the `{ "ignoreReadonlyClassProperties": false }` option:
|
||||
|
||||
```ts option='{ "ignoreReadonlyClassProperties": false }' showPlaygroundButton
|
||||
class Foo {
|
||||
readonly A = 1;
|
||||
readonly B = 2;
|
||||
public static readonly C = 1;
|
||||
static readonly D = 1;
|
||||
}
|
||||
```
|
||||
|
||||
Examples of **correct** code for the `{ "ignoreReadonlyClassProperties": true }` option:
|
||||
|
||||
```ts option='{ "ignoreReadonlyClassProperties": true }' showPlaygroundButton
|
||||
class Foo {
|
||||
readonly A = 1;
|
||||
readonly B = 2;
|
||||
public static readonly C = 1;
|
||||
static readonly D = 1;
|
||||
}
|
||||
```
|
||||
|
||||
### `ignoreTypeIndexes`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Whether numbers used to index types are okay. `false` by default.
|
||||
|
||||
Examples of **incorrect** code for the `{ "ignoreTypeIndexes": false }` option:
|
||||
|
||||
```ts option='{ "ignoreTypeIndexes": false }' showPlaygroundButton
|
||||
type Foo = Bar[0];
|
||||
type Baz = Parameters<Foo>[2];
|
||||
```
|
||||
|
||||
Examples of **correct** code for the `{ "ignoreTypeIndexes": true }` option:
|
||||
|
||||
```ts option='{ "ignoreTypeIndexes": true }' showPlaygroundButton
|
||||
type Foo = Bar[0];
|
||||
type Baz = Parameters<Foo>[2];
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project frequently deals with constant numbers and you don't wish to take up extra space to declare them, this rule might not be for you.
|
||||
We recommend at least using descriptive comments and/or names to describe constants.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) instead of completely disabling this rule.
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
---
|
||||
description: 'Disallow the `void` operator except when used to discard a value.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-meaningless-void-operator** for documentation.
|
||||
|
||||
`void` in TypeScript refers to a function return that is meant to be ignored.
|
||||
The `void` operator is a useful tool to convey the programmer's intent to discard a value.
|
||||
For example, it is recommended as one way of suppressing [`@typescript-eslint/no-floating-promises`](./no-floating-promises.mdx) instead of adding `.catch()` to a promise.
|
||||
|
||||
This rule helps an authors 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.
|
||||
This rule reports on any `void` operator whose argument is already of type `void` or `undefined`.
|
||||
|
||||
## Examples
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
void (() => {})();
|
||||
|
||||
function foo() {}
|
||||
void foo();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
(() => {})();
|
||||
|
||||
function foo() {}
|
||||
foo(); // nothing to discard
|
||||
|
||||
function bar(x: number) {
|
||||
void x; // discarding a number
|
||||
return 2;
|
||||
}
|
||||
void bar(1); // discarding a number
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `checkNever`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't mind extra `void`s in your project, you can avoid this rule.
|
||||
53
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-misused-new.mdx
generated
vendored
53
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-misused-new.mdx
generated
vendored
|
|
@ -1,53 +0,0 @@
|
|||
---
|
||||
description: 'Enforce valid definition of `new` and `constructor`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-misused-new** for documentation.
|
||||
|
||||
JavaScript classes may define a `constructor` method that runs when a class instance is newly created.
|
||||
TypeScript allows interfaces that describe a static class object to define a `new()` method (though this is rarely used in real world code).
|
||||
Developers new to JavaScript classes and/or TypeScript interfaces may sometimes confuse when to use `constructor` or `new`.
|
||||
|
||||
This rule reports when a class defines a method named `new` or an interface defines a method named `constructor`.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
declare class C {
|
||||
new(): C;
|
||||
}
|
||||
|
||||
interface I {
|
||||
new (): I;
|
||||
constructor(): void;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
declare class C {
|
||||
constructor();
|
||||
}
|
||||
|
||||
interface I {
|
||||
new (): C;
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you intentionally want a class with a `new` method, and you're confident nobody working in your code will mistake it with a constructor, you might not want this rule.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
314
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-misused-promises.mdx
generated
vendored
314
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-misused-promises.mdx
generated
vendored
|
|
@ -1,314 +0,0 @@
|
|||
---
|
||||
description: 'Disallow Promises in places not designed to handle them.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-misused-promises** for documentation.
|
||||
|
||||
This rule forbids providing Promises to logical locations such as if statements in places where the TypeScript compiler allows them but they are not handled properly.
|
||||
These situations can often arise due to a missing `await` keyword or just a misunderstanding of the way async
|
||||
functions are handled/awaited.
|
||||
|
||||
:::tip
|
||||
`no-misused-promises` only detects code that provides Promises to incorrect _logical_ locations.
|
||||
See [`no-floating-promises`](./no-floating-promises.mdx) for detecting unhandled Promise _statements_.
|
||||
:::
|
||||
|
||||
## Options
|
||||
|
||||
### `checksConditionals`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
If you don't want to check conditionals, you can configure the rule with `"checksConditionals": false`:
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/no-misused-promises": [
|
||||
"error",
|
||||
{
|
||||
"checksConditionals": false
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Doing so prevents the rule from looking at code like `if (somePromise)`.
|
||||
|
||||
### `checksVoidReturn`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Likewise, if you don't want to check functions that return promises where a void return is
|
||||
expected, your configuration will look like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/no-misused-promises": [
|
||||
"error",
|
||||
{
|
||||
"checksVoidReturn": false
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can disable selective parts of the `checksVoidReturn` option by providing an object that disables specific checks. For example, if you don't mind that passing a `() => Promise<void>` to a `() => void` parameter or JSX attribute can lead to a floating unhandled Promise:
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/no-misused-promises": [
|
||||
"error",
|
||||
{
|
||||
"checksVoidReturn": {
|
||||
"arguments": false,
|
||||
"attributes": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The following sub-options are supported:
|
||||
|
||||
#### `arguments`
|
||||
|
||||
Disables checking an asynchronous function passed as argument where the parameter type expects a function that returns `void`.
|
||||
|
||||
#### `attributes`
|
||||
|
||||
Disables checking an asynchronous function passed as a JSX attribute expected to be a function that returns `void`.
|
||||
|
||||
#### `inheritedMethods`
|
||||
|
||||
Disables checking an asynchronous method in a type that extends or implements another type expecting that method to return `void`.
|
||||
|
||||
:::note
|
||||
For now, `no-misused-promises` only checks _named_ methods against extended/implemented types: that is, call/construct/index signatures are ignored. Call signatures are not required in TypeScript to be consistent with one another, and construct signatures cannot be `async` in the first place. Index signature checking may be implemented in the future.
|
||||
:::
|
||||
|
||||
#### `properties`
|
||||
|
||||
Disables checking an asynchronous function passed as an object property expected to be a function that returns `void`.
|
||||
|
||||
#### `returns`
|
||||
|
||||
Disables checking an asynchronous function returned in a function whose return type is a function that returns `void`.
|
||||
|
||||
#### `variables`
|
||||
|
||||
Disables checking an asynchronous function used as a variable whose return type is a function that returns `void`.
|
||||
|
||||
### `checksSpreads`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
If you don't want to check object spreads, you can add this configuration:
|
||||
|
||||
```json
|
||||
{
|
||||
"@typescript-eslint/no-misused-promises": [
|
||||
"error",
|
||||
{
|
||||
"checksSpreads": false
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### `checksConditionals`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `checksConditionals: true`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "checksConditionals": true }'
|
||||
const promise = Promise.resolve('value');
|
||||
|
||||
if (promise) {
|
||||
// Do something
|
||||
}
|
||||
|
||||
const val = promise ? 123 : 456;
|
||||
|
||||
[1, 2, 3].filter(() => promise);
|
||||
|
||||
while (promise) {
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "checksConditionals": true }'
|
||||
const promise = Promise.resolve('value');
|
||||
|
||||
// Always `await` the Promise in a conditional
|
||||
if (await promise) {
|
||||
// Do something
|
||||
}
|
||||
|
||||
const val = (await promise) ? 123 : 456;
|
||||
|
||||
const returnVal = await promise;
|
||||
[1, 2, 3].filter(() => returnVal);
|
||||
|
||||
while (await promise) {
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `checksVoidReturn`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `checksVoidReturn: true`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "checksVoidReturn": true }'
|
||||
[1, 2, 3].forEach(async value => {
|
||||
await fetch(`/${value}`);
|
||||
});
|
||||
|
||||
new Promise<void>(async (resolve, reject) => {
|
||||
await fetch('/');
|
||||
resolve();
|
||||
});
|
||||
|
||||
document.addEventListener('click', async () => {
|
||||
console.log('synchronous call');
|
||||
await fetch('/');
|
||||
console.log('synchronous call');
|
||||
});
|
||||
|
||||
interface MySyncInterface {
|
||||
setThing(): void;
|
||||
}
|
||||
class MyClass implements MySyncInterface {
|
||||
async setThing(): Promise<void> {
|
||||
this.thing = await fetchThing();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "checksVoidReturn": true }'
|
||||
// for-of puts `await` in outer context
|
||||
for (const value of [1, 2, 3]) {
|
||||
await doSomething(value);
|
||||
}
|
||||
|
||||
// If outer context is not `async`, handle error explicitly
|
||||
Promise.all(
|
||||
[1, 2, 3].map(async value => {
|
||||
await doSomething(value);
|
||||
}),
|
||||
).catch(handleError);
|
||||
|
||||
// Use an async IIFE wrapper
|
||||
new Promise((resolve, reject) => {
|
||||
// combine with `void` keyword to tell `no-floating-promises` rule to ignore unhandled rejection
|
||||
void (async () => {
|
||||
await doSomething();
|
||||
resolve();
|
||||
})();
|
||||
});
|
||||
|
||||
// Name the async wrapper to call it later
|
||||
document.addEventListener('click', () => {
|
||||
const handler = async () => {
|
||||
await doSomething();
|
||||
otherSynchronousCall();
|
||||
};
|
||||
|
||||
try {
|
||||
synchronousCall();
|
||||
} catch (err) {
|
||||
handleSpecificError(err);
|
||||
}
|
||||
|
||||
handler().catch(handleError);
|
||||
});
|
||||
|
||||
interface MyAsyncInterface {
|
||||
setThing(): Promise<void>;
|
||||
}
|
||||
class MyClass implements MyAsyncInterface {
|
||||
async setThing(): Promise<void> {
|
||||
this.thing = await fetchThing();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `checksSpreads`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for this rule with `checksSpreads: true`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "checksSpreads": true }'
|
||||
const getData = () => fetch('/');
|
||||
|
||||
console.log({ foo: 42, ...getData() });
|
||||
|
||||
const awaitData = async () => {
|
||||
await fetch('/');
|
||||
};
|
||||
|
||||
console.log({ foo: 42, ...awaitData() });
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "checksSpreads": true }'
|
||||
const getData = () => fetch('/');
|
||||
|
||||
console.log({ foo: 42, ...(await getData()) });
|
||||
|
||||
const awaitData = async () => {
|
||||
await fetch('/');
|
||||
};
|
||||
|
||||
console.log({ foo: 42, ...(await awaitData()) });
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
This rule can be difficult to enable on large existing projects that set up many misused Promises.
|
||||
Alternately, if you're not worried about crashes from floating or misused Promises -such as if you have global unhandled Promise handlers registered- then in some cases it may be safe to not use this rule.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [TypeScript void function assignability](https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void)
|
||||
|
||||
## Related To
|
||||
|
||||
- [`no-floating-promises`](./no-floating-promises.mdx)
|
||||
132
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-misused-spread.mdx
generated
vendored
132
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-misused-spread.mdx
generated
vendored
|
|
@ -1,132 +0,0 @@
|
|||
---
|
||||
description: 'Disallow using the spread operator when it might cause unexpected behavior.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-misused-spread** for documentation.
|
||||
|
||||
[Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) (`...`) is a JavaScript feature for creating an object with the joined properties of one or more other objects.
|
||||
TypeScript allows spreading objects whose properties are not typically meant to be enumerated, such as arrays and class instances.
|
||||
|
||||
This rule disallows using the spread syntax on values whose types indicate doing so may cause unexpected behavior.
|
||||
That includes the following cases:
|
||||
|
||||
- Spreading a `Promise` into an object.
|
||||
You probably meant to `await` it.
|
||||
- Spreading a function without properties into an object.
|
||||
You probably meant to call it.
|
||||
- Spreading an iterable (`Array`, `Map`, etc.) into an object.
|
||||
Iterable objects usually do not have meaningful enumerable properties and you probably meant to spread it into an array instead.
|
||||
- Spreading a string into an array.
|
||||
String enumeration behaviors in JavaScript around encoded characters are often surprising.
|
||||
- Spreading a `class` into an object.
|
||||
This copies all static own properties of the class, but none of the inheritance chain.
|
||||
- Spreading a class instance into an object.
|
||||
This does not faithfully copy the instance because only its own properties are copied, but the inheritance chain is lost, including all its methods.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
declare const promise: Promise<number>;
|
||||
const spreadPromise = { ...promise };
|
||||
|
||||
declare function getObject(): Record<string, strings>;
|
||||
const getObjectSpread = { ...getObject };
|
||||
|
||||
declare const map: Map<string, number>;
|
||||
const mapSpread = { ...map };
|
||||
|
||||
declare const userName: string;
|
||||
const characters = [...userName];
|
||||
```
|
||||
|
||||
```ts
|
||||
declare class Box {
|
||||
value: number;
|
||||
}
|
||||
const boxSpread = { ...Box };
|
||||
|
||||
declare const instance: Box;
|
||||
const instanceSpread = { ...instance };
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
declare const promise: Promise<number>;
|
||||
const spreadPromise = { ...(await promise) };
|
||||
|
||||
declare function getObject(): Record<string, strings>;
|
||||
const getObjectSpread = { ...getObject() };
|
||||
|
||||
declare const map: Map<string, number>;
|
||||
const mapObject = Object.fromEntries(map);
|
||||
|
||||
declare const userName: string;
|
||||
const characters = userName.split('');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allow`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This option takes the shared [`TypeOrValueSpecifier` format](/packages/type-utils/type-or-value-specifier).
|
||||
|
||||
Examples of a configuration for this option in a `file.ts` file:
|
||||
|
||||
```json
|
||||
"@typescript-eslint/no-misused-spread": [
|
||||
"error",
|
||||
{
|
||||
"allow": [
|
||||
{ "from": "file", "name": "BrandedString", "path": "file.ts" },
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{"allow":[{ "from": "file", "name": "BrandedString" }]}'
|
||||
declare const unbrandedString: string;
|
||||
|
||||
const spreadUnbrandedString = [...unbrandedString];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{"allow":[{ "from": "file", "name": "BrandedString" }]}'
|
||||
type BrandedString = string & { __brand: 'safe' };
|
||||
|
||||
declare const brandedString: BrandedString;
|
||||
|
||||
const spreadBrandedString = [...brandedString];
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your application intentionally works with raw data in unusual ways, such as directly manipulating class prototype chains, you might not want this rule.
|
||||
|
||||
If your use cases for unusual spreads only involve a few types, you might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) and/or the [`allow` option](#allow) instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [Strings Shouldn't Be Iterable By Default](https://www.xanthir.com/b4wJ1)
|
||||
96
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-mixed-enums.mdx
generated
vendored
96
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-mixed-enums.mdx
generated
vendored
|
|
@ -1,96 +0,0 @@
|
|||
---
|
||||
description: 'Disallow enums from having both number and string members.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-mixed-enums** for documentation.
|
||||
|
||||
TypeScript enums are allowed to assign numeric or string values to their members.
|
||||
Most enums contain either all numbers or all strings, but in theory you can mix-and-match within the same enum.
|
||||
Mixing enum member types is generally considered confusing and a bad practice.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
enum Status {
|
||||
Unknown,
|
||||
Closed = 1,
|
||||
Open = 'open',
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct (Explicit Numbers)">
|
||||
|
||||
```ts
|
||||
enum Status {
|
||||
Unknown = 0,
|
||||
Closed = 1,
|
||||
Open = 2,
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct (Implicit Numbers)">
|
||||
|
||||
```ts
|
||||
enum Status {
|
||||
Unknown,
|
||||
Closed,
|
||||
Open,
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct (Strings)">
|
||||
|
||||
```ts
|
||||
enum Status {
|
||||
Unknown = 'unknown',
|
||||
Closed = 'closed',
|
||||
Open = 'open',
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Iteration Pitfalls of Mixed Enum Member Values
|
||||
|
||||
Enum values may be iterated over using `Object.entries`/`Object.keys`/`Object.values`.
|
||||
|
||||
If all enum members are strings, the number of items will match the number of enum members:
|
||||
|
||||
```ts
|
||||
enum Status {
|
||||
Closed = 'closed',
|
||||
Open = 'open',
|
||||
}
|
||||
|
||||
// ['closed', 'open']
|
||||
Object.values(Status);
|
||||
```
|
||||
|
||||
But if the enum contains members that are initialized with numbers -including implicitly initialized numbers— then iteration over that enum will include those numbers as well:
|
||||
|
||||
```ts
|
||||
enum Status {
|
||||
Unknown,
|
||||
Closed = 1,
|
||||
Open = 'open',
|
||||
}
|
||||
|
||||
// ["Unknown", "Closed", 0, 1, "open"]
|
||||
Object.values(Status);
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you don't mind the confusion of mixed enum member values and don't iterate over enums, you can safely disable this rule.
|
||||
157
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-namespace.mdx
generated
vendored
157
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-namespace.mdx
generated
vendored
|
|
@ -1,157 +0,0 @@
|
|||
---
|
||||
description: 'Disallow TypeScript namespaces.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-namespace** for documentation.
|
||||
|
||||
TypeScript historically allowed a form of code organization called "custom modules" (`module Example {}`), later renamed to "namespaces" (`namespace Example`).
|
||||
Namespaces are an outdated way to organize TypeScript code.
|
||||
ES2015 module syntax is now preferred (`import`/`export`).
|
||||
|
||||
> This rule does not report on the use of TypeScript module declarations to describe external APIs (`declare module 'foo' {}`).
|
||||
|
||||
## Examples
|
||||
|
||||
Examples of code with the default options:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
module foo {}
|
||||
namespace foo {}
|
||||
|
||||
declare module foo {}
|
||||
declare namespace foo {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
declare module 'foo' {}
|
||||
|
||||
// anything inside a d.ts file
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allowDeclarations`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code with the `{ "allowDeclarations": true }` option:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowDeclarations": true }'
|
||||
module foo {}
|
||||
namespace foo {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowDeclarations": true }'
|
||||
declare module 'foo' {}
|
||||
declare module foo {}
|
||||
declare namespace foo {}
|
||||
|
||||
declare global {
|
||||
namespace foo {}
|
||||
}
|
||||
|
||||
declare module foo {
|
||||
namespace foo {}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
Examples of code for the `{ "allowDeclarations": false }` option:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowDeclarations": false }'
|
||||
module foo {}
|
||||
namespace foo {}
|
||||
declare module foo {}
|
||||
declare namespace foo {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowDeclarations": false }'
|
||||
declare module 'foo' {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowDefinitionFiles`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Examples of code for the `{ "allowDefinitionFiles": true }` option:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowDefinitionFiles": true }'
|
||||
// if outside a d.ts file
|
||||
module foo {}
|
||||
namespace foo {}
|
||||
|
||||
// if outside a d.ts file and allowDeclarations = false
|
||||
module foo {}
|
||||
namespace foo {}
|
||||
declare module foo {}
|
||||
declare namespace foo {}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowDefinitionFiles": true }'
|
||||
declare module 'foo' {}
|
||||
|
||||
// anything inside a d.ts file
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project uses TypeScript's CommonJS export syntax (`export = ...`), you may need to use namespaces in order to export types from your module.
|
||||
You can learn more about this at:
|
||||
|
||||
- [TypeScript#52203](https://github.com/microsoft/TypeScript/pull/52203), the pull request introducing [`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax)
|
||||
- [TypeScript#60852](https://github.com/microsoft/TypeScript/issues/60852), an issue requesting syntax to export types from a CommonJS module.
|
||||
|
||||
If your project uses this syntax, either because it was architected before modern modules and namespaces, or because a module option such as `verbatimModuleSyntax` requires it, it may be difficult to migrate off of namespaces.
|
||||
In that case you may not be able to use this rule for parts of your project.
|
||||
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
{/* cspell:disable-next-line */}
|
||||
|
||||
- [FAQ: I get errors from the `@typescript-eslint/no-namespace` and/or `no-var` rules about declaring global variables](/troubleshooting/faqs/eslint#i-get-errors-from-the-typescript-eslintno-namespace-andor-no-var-rules-about-declaring-global-variables)
|
||||
- [FAQ: How should I handle reports that conflict with verbatimModuleSyntax?](/troubleshooting/faqs/typescript#how-should-i-handle-reports-that-conflict-with-verbatimmodulesyntax)
|
||||
- [TypeScript handbook entry on Modules](https://www.typescriptlang.org/docs/handbook/modules.html)
|
||||
- [TypeScript handbook entry on Namespaces](https://www.typescriptlang.org/docs/handbook/namespaces.html)
|
||||
- [TypeScript handbook entry on Namespaces and Modules](https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html)
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
---
|
||||
description: 'Disallow non-null assertions in the left operand of a nullish coalescing operator.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-non-null-asserted-nullish-coalescing** for documentation.
|
||||
|
||||
The `??` nullish coalescing runtime operator allows providing a default value when dealing with `null` or `undefined`.
|
||||
Using a `!` non-null assertion type operator in the left operand of a nullish coalescing operator is redundant, and likely a sign of programmer error or confusion over the two operators.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
foo! ?? bar;
|
||||
foo.bazz! ?? bar;
|
||||
foo!.bazz! ?? bar;
|
||||
foo()! ?? bar;
|
||||
|
||||
let x!: string;
|
||||
x! ?? '';
|
||||
|
||||
let x: string;
|
||||
x = foo();
|
||||
x! ?? '';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
foo ?? bar;
|
||||
foo ?? bar!;
|
||||
foo!.bazz ?? bar;
|
||||
foo!.bazz ?? bar!;
|
||||
foo() ?? bar;
|
||||
|
||||
// This is considered correct code because there's no way for the user to satisfy it.
|
||||
let x: string;
|
||||
x! ?? '';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project's types don't yet fully describe whether certain values may be nullable, such as if you're transitioning to `strictNullChecks`, this rule might create many false reports.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [TypeScript 3.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html)
|
||||
- [Nullish Coalescing Proposal](https://github.com/tc39/proposal-nullish-coalescing)
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
---
|
||||
description: 'Disallow non-null assertions after an optional chain expression.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-non-null-asserted-optional-chain** for documentation.
|
||||
|
||||
`?.` optional chain expressions provide `undefined` if an object is `null` or `undefined`.
|
||||
Using a `!` non-null assertion to assert the result of an `?.` optional chain expression is non-nullable is likely wrong.
|
||||
|
||||
> Most of the time, either the object was not nullable and did not need the `?.` for its property lookup, or the `!` is incorrect and introducing a type safety hole.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
foo?.bar!;
|
||||
foo?.bar()!;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
foo?.bar;
|
||||
foo?.bar();
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project's types don't yet fully describe whether certain values may be nullable, such as if you're transitioning to `strictNullChecks`, this rule might create many false reports.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [TypeScript 3.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html)
|
||||
- [Optional Chaining Proposal](https://github.com/tc39/proposal-optional-chaining/)
|
||||
48
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-non-null-assertion.mdx
generated
vendored
48
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-non-null-assertion.mdx
generated
vendored
|
|
@ -1,48 +0,0 @@
|
|||
---
|
||||
description: 'Disallow non-null assertions using the `!` postfix operator.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-non-null-assertion** for documentation.
|
||||
|
||||
TypeScript's `!` non-null assertion operator asserts to the type system that an expression is non-nullable, as in not `null` or `undefined`.
|
||||
Using assertions to tell the type system new information is often a sign that code is not fully type-safe.
|
||||
It's generally better to structure program logic so that TypeScript understands when values may be nullable.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
interface Example {
|
||||
property?: string;
|
||||
}
|
||||
|
||||
declare const example: Example;
|
||||
const includesBaz = example.property!.includes('baz');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
interface Example {
|
||||
property?: string;
|
||||
}
|
||||
|
||||
declare const example: Example;
|
||||
const includesBaz = example.property?.includes('baz') ?? false;
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project's types don't yet fully describe whether certain values may be nullable, such as if you're transitioning to `strictNullChecks`, this rule might create many false reports.
|
||||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
16
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-parameter-properties.mdx
generated
vendored
16
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-parameter-properties.mdx
generated
vendored
|
|
@ -1,16 +0,0 @@
|
|||
---
|
||||
displayed_sidebar: rulesSidebar
|
||||
---
|
||||
|
||||
:::danger Deprecated
|
||||
|
||||
This rule has been deprecated in favour of the [`parameter-properties`](https://typescript-eslint.io/rules/parameter-properties/) rule.
|
||||
|
||||
:::
|
||||
|
||||
<!--
|
||||
This doc file has been left on purpose to help direct people to the replacement rule.
|
||||
|
||||
Note that there is no actual way to get to this page in the normal navigation,
|
||||
so end-users will only be able to get to this page from the search bar.
|
||||
-->
|
||||
79
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-redeclare.mdx
generated
vendored
79
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-redeclare.mdx
generated
vendored
|
|
@ -1,79 +0,0 @@
|
|||
---
|
||||
description: 'Disallow variable redeclaration.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-redeclare** for documentation.
|
||||
|
||||
import TypeScriptOverlap from '@site/src/components/TypeScriptOverlap';
|
||||
|
||||
<TypeScriptOverlap />
|
||||
|
||||
It adds support for TypeScript function overloads, and declaration merging.
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
interface Options extends BaseNoRedeclareOptions {
|
||||
ignoreDeclarationMerge?: boolean;
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
...baseNoRedeclareDefaultOptions,
|
||||
ignoreDeclarationMerge: true,
|
||||
};
|
||||
```
|
||||
|
||||
### `ignoreDeclarationMerge`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
The following sets will be ignored when this option is enabled:
|
||||
|
||||
- interface + interface
|
||||
- namespace + namespace
|
||||
- class + interface
|
||||
- class + namespace
|
||||
- class + interface + namespace
|
||||
- function + namespace
|
||||
- enum + namespace
|
||||
|
||||
Examples of **correct** code with `{ ignoreDeclarationMerge: true }`:
|
||||
|
||||
```ts option='{ "ignoreDeclarationMerge": true }' showPlaygroundButton
|
||||
interface A {
|
||||
prop1: 1;
|
||||
}
|
||||
interface A {
|
||||
prop2: 2;
|
||||
}
|
||||
|
||||
namespace Foo {
|
||||
export const a = 1;
|
||||
}
|
||||
namespace Foo {
|
||||
export const b = 2;
|
||||
}
|
||||
|
||||
class Bar {}
|
||||
namespace Bar {}
|
||||
|
||||
function Baz() {}
|
||||
namespace Baz {}
|
||||
```
|
||||
|
||||
**Note:** Even with this option set to true, this rule will report if you name a type and a variable the same name. **_This is intentional_**.
|
||||
Declaring a variable and a type the same is usually an accident, and it can lead to hard-to-understand code.
|
||||
If you have a rare case where you're intentionally naming a type the same name as a variable, use a disable comment. For example:
|
||||
|
||||
```ts option='{ "ignoreDeclarationMerge": true }' showPlaygroundButton
|
||||
type something = string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare -- intentionally naming the variable the same as the type
|
||||
const something = 2;
|
||||
```
|
||||
102
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-redundant-type-constituents.mdx
generated
vendored
102
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-redundant-type-constituents.mdx
generated
vendored
|
|
@ -1,102 +0,0 @@
|
|||
---
|
||||
description: 'Disallow members of unions and intersections that do nothing or override type information.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-redundant-type-constituents** for documentation.
|
||||
|
||||
Some types can override some other types ("constituents") in a union or intersection and/or be overridden by some other types.
|
||||
TypeScript's set theory of types includes cases where a constituent type might be useless in the parent union or intersection.
|
||||
|
||||
Within `|` unions:
|
||||
|
||||
- `any` and `unknown` "override" all other union members
|
||||
- `never` is dropped from unions in any position except when in a return type position
|
||||
- primitive types such as `string` "override" any of their literal types such as `""`
|
||||
|
||||
Within `&` intersections:
|
||||
|
||||
- `any` and `never` "override" all other intersection members
|
||||
- `unknown` is dropped from intersections
|
||||
- literal types "override" any primitive types in an intersection
|
||||
- literal types such as `""` "override" any of their primitive types such as `string`
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
type UnionAny = any | 'foo';
|
||||
type UnionUnknown = unknown | 'foo';
|
||||
type UnionNever = never | 'foo';
|
||||
|
||||
type UnionBooleanLiteral = boolean | false;
|
||||
type UnionNumberLiteral = number | 1;
|
||||
type UnionStringLiteral = string | 'foo';
|
||||
|
||||
type IntersectionAny = any & 'foo';
|
||||
type IntersectionUnknown = string & unknown;
|
||||
type IntersectionNever = string | never;
|
||||
|
||||
type IntersectionBooleanLiteral = boolean & false;
|
||||
type IntersectionNumberLiteral = number & 1;
|
||||
type IntersectionStringLiteral = string & 'foo';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
type UnionAny = any;
|
||||
type UnionUnknown = unknown;
|
||||
type UnionNever = never;
|
||||
|
||||
type UnionBooleanLiteral = boolean;
|
||||
type UnionNumberLiteral = number;
|
||||
type UnionStringLiteral = string;
|
||||
|
||||
type IntersectionAny = any;
|
||||
type IntersectionUnknown = string;
|
||||
type IntersectionNever = string;
|
||||
|
||||
type IntersectionBooleanLiteral = false;
|
||||
type IntersectionNumberLiteral = 1;
|
||||
type IntersectionStringLiteral = 'foo';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Limitations
|
||||
|
||||
This rule plays it safe and only works with bottom types, top types, and comparing literal types to primitive types.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
Some projects choose to occasionally intentionally include a redundant type constituent for documentation purposes.
|
||||
For example, the following code includes `string` in a union even though the `unknown` makes it redundant:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* Normally a string name, but sometimes arbitrary unknown data.
|
||||
*/
|
||||
type NameOrOther = string | unknown;
|
||||
```
|
||||
|
||||
If you strongly feel a preference for these unnecessary type constituents, this rule might not be for you.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [Union Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
|
||||
- [Intersection Types](https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types)
|
||||
- [Bottom Types](https://en.wikipedia.org/wiki/Bottom_type)
|
||||
- [Top Types](https://en.wikipedia.org/wiki/Top_type)
|
||||
|
||||
## Related To
|
||||
|
||||
- [no-duplicate-type-constituents](./no-duplicate-type-constituents.mdx)
|
||||
114
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-require-imports.mdx
generated
vendored
114
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-require-imports.mdx
generated
vendored
|
|
@ -1,114 +0,0 @@
|
|||
---
|
||||
description: 'Disallow invocation of `require()`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-require-imports** for documentation.
|
||||
|
||||
Depending on your TSConfig settings and whether you're authoring ES Modules or CommonJS, TS may allow both `import` and `require()` to be used, even within a single file.
|
||||
|
||||
This rule enforces that you use the newer ES Module `import` syntax over CommonJS `require()`.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
const lib1 = require('lib1');
|
||||
const { lib2 } = require('lib2');
|
||||
import lib3 = require('lib3');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
import * as lib1 from 'lib1';
|
||||
import { lib2 } from 'lib2';
|
||||
import * as lib3 from 'lib3';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allow`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
These strings will be compiled into regular expressions with the `u` flag and be used to test against the imported path. A common use case is to allow importing `package.json`. This is because `package.json` commonly lives outside of the TS root directory, so statically importing it would lead to root directory conflicts, especially with `resolveJsonModule` enabled. You can also use it to allow importing any JSON if your environment doesn't support JSON modules, or use it for other cases where `import` statements cannot work.
|
||||
|
||||
With `{ allow: ['/package\\.json$'] }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allow": ["/package.json$"] }'
|
||||
console.log(require('../data.json').version);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allow": ["/package.json$"] }'
|
||||
console.log(require('../package.json').version);
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowAsImport`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
When set to `true`, `import ... = require(...)` declarations won't be reported.
|
||||
This is beneficial if you use certain module options that require strict CommonJS interop semantics, such as [verbatimModuleSyntax](https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax).
|
||||
|
||||
With `{ allowAsImport: true }`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowAsImport": true }'
|
||||
var foo = require('foo');
|
||||
const foo = require('foo');
|
||||
let foo = require('foo');
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowAsImport": true }'
|
||||
import foo = require('foo');
|
||||
import foo from 'foo';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Usage with CommonJS
|
||||
|
||||
While this rule is primarily intended to promote ES Module syntax, it still makes sense to enable this rule when authoring CommonJS modules.
|
||||
|
||||
If you prefer to use TypeScript's built-in `import ... from ...` ES Module syntax, which is transformed to `require()` calls during transpilation when outputting CommonJS, you can use the rule's default behavior.
|
||||
|
||||
If, instead, you prefer to use `require()` syntax, we recommend you use this rule with [`allowAsImport`](#allowAsImport) enabled.
|
||||
That way, you still enforce usage of `import ... = require(...)` rather than bare `require()` calls, which are not statically analyzed by TypeScript.
|
||||
We don't directly a way to _prohibit_ ES Module syntax from being used; consider instead using TypeScript's [`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig/#verbatimModuleSyntax) option if you find yourself in a situation where you would want this.
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you are authoring CommonJS modules _and_ your project frequently uses dynamic `require`s, then this rule might not be applicable to you.
|
||||
Otherwise the `allowAsImport` option probably suits your needs.
|
||||
|
||||
If only a subset of your project uses dynamic `require`s then you might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`no-var-requires`](./no-var-requires.mdx)
|
||||
84
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-restricted-imports.mdx
generated
vendored
84
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-restricted-imports.mdx
generated
vendored
|
|
@ -1,84 +0,0 @@
|
|||
---
|
||||
description: 'Disallow specified modules when loaded by `import`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-restricted-imports** for documentation.
|
||||
|
||||
It adds support for type import syntaxes:
|
||||
|
||||
- `import type X from "..."`
|
||||
- `import { type X } from "..."`
|
||||
- `import x = require("...")`
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
### `allowTypeImports`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Whether to allow type-only imports for a path.
|
||||
Default: `false`.
|
||||
|
||||
You can specify this option for a specific path or pattern as follows:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"rules": {
|
||||
"@typescript-eslint/no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"paths": [
|
||||
{
|
||||
"name": "import-foo",
|
||||
"message": "Please use import-bar instead.",
|
||||
"allowTypeImports": true,
|
||||
},
|
||||
{
|
||||
"name": "import-baz",
|
||||
"message": "Please use import-quux instead.",
|
||||
"allowTypeImports": true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Whether to allow [Type-Only Imports](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export).
|
||||
|
||||
Examples of code with the above config:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{"paths":[{"name":"import-foo","message":"Please use import-bar instead.","allowTypeImports":true},{"name":"import-baz","message":"Please use import-quux instead.","allowTypeImports":true}]}'
|
||||
import foo from 'import-foo';
|
||||
export { Foo } from 'import-foo';
|
||||
|
||||
import baz from 'import-baz';
|
||||
export { Baz } from 'import-baz';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{"paths":[{"name":"import-foo","message":"Please use import-bar instead.","allowTypeImports":true},{"name":"import-baz","message":"Please use import-quux instead.","allowTypeImports":true}]}'
|
||||
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';
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
70
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-restricted-types.mdx
generated
vendored
70
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-restricted-types.mdx
generated
vendored
|
|
@ -1,70 +0,0 @@
|
|||
---
|
||||
description: 'Disallow certain types.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-restricted-types** for documentation.
|
||||
|
||||
It can sometimes be useful to ban specific types from being used in type annotations.
|
||||
For example, a project might be migrating from using one type to another, and want to ban references to the old type.
|
||||
|
||||
This rule can be configured to ban a list of specific types and can suggest alternatives.
|
||||
Note that it does not ban the corresponding runtime objects from being used.
|
||||
|
||||
## Options
|
||||
|
||||
### `types`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
The type can either be a type name literal (`OldType`) or a a type name with generic parameter instantiation(s) (`OldType<MyArgument>`).
|
||||
|
||||
The values can be:
|
||||
|
||||
- A string, which is the error message to be reported; or
|
||||
- An object with the following properties:
|
||||
- `message: string`: the message to display when the type is matched.
|
||||
- `fixWith?: string`: a string to replace the banned type with when the fixer is run. If this is omitted, no fix will be done.
|
||||
- `suggest?: string[]`: a list of suggested replacements for the banned type.
|
||||
|
||||
Example configuration:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"@typescript-eslint/no-restricted-types": [
|
||||
"error",
|
||||
{
|
||||
"types": {
|
||||
// add a custom message to help explain why not to use it
|
||||
"OldType": "Don't use OldType because it is unsafe",
|
||||
|
||||
// add a custom message, and tell the plugin how to fix it
|
||||
"OldAPI": {
|
||||
"message": "Use NewAPI instead",
|
||||
"fixWith": "NewAPI",
|
||||
},
|
||||
|
||||
// add a custom message, and tell the plugin how to suggest a fix
|
||||
"SoonToBeOldAPI": {
|
||||
"message": "Use NewAPI instead",
|
||||
"suggest": ["NewAPIOne", "NewAPITwo"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If you have no need to ban specific types from being used in type annotations, you don't need this rule.
|
||||
|
||||
## Related To
|
||||
|
||||
- [`no-empty-object-type`](./no-empty-object-type.mdx)
|
||||
- [`no-unsafe-function-type`](./no-unsafe-function-type.mdx)
|
||||
- [`no-wrapper-object-types`](./no-wrapper-object-types.mdx)
|
||||
143
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-shadow.mdx
generated
vendored
143
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-shadow.mdx
generated
vendored
|
|
@ -1,143 +0,0 @@
|
|||
---
|
||||
description: 'Disallow variable declarations from shadowing variables declared in the outer scope.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-shadow** for documentation.
|
||||
|
||||
It adds support for TypeScript's `this` parameters and global augmentation, and adds options for TypeScript features.
|
||||
|
||||
## Options
|
||||
|
||||
This rule adds the following options:
|
||||
|
||||
```ts
|
||||
type AdditionalHoistOptionEntries = 'types' | 'functions-and-types';
|
||||
|
||||
type HoistOptionEntries =
|
||||
| BaseNoShadowHoistOptionEntries
|
||||
| AdditionalHoistOptionEntries;
|
||||
|
||||
interface Options extends BaseNoShadowOptions {
|
||||
hoist?: HoistOptionEntries;
|
||||
ignoreTypeValueShadow?: boolean;
|
||||
ignoreFunctionTypeParameterNameValueShadow?: boolean;
|
||||
}
|
||||
|
||||
const defaultOptions: Options = {
|
||||
...baseNoShadowDefaultOptions,
|
||||
hoist: 'functions-and-types',
|
||||
ignoreTypeValueShadow: true,
|
||||
ignoreFunctionTypeParameterNameValueShadow: true,
|
||||
};
|
||||
```
|
||||
|
||||
### hoist: `types`
|
||||
|
||||
Examples of incorrect code for the `{ "hoist": "types" }` option:
|
||||
|
||||
```ts option='{ "hoist": "types" }' showPlaygroundButton
|
||||
type Bar<Foo> = 1;
|
||||
type Foo = 1;
|
||||
```
|
||||
|
||||
### hoist: `functions-and-types`
|
||||
|
||||
Examples of incorrect code for the `{ "hoist": "functions-and-types" }` option:
|
||||
|
||||
```ts option='{ "hoist": "functions-and-types" }' showPlaygroundButton
|
||||
// types
|
||||
type Bar<Foo> = 1;
|
||||
type Foo = 1;
|
||||
|
||||
// functions
|
||||
if (true) {
|
||||
let b = 6;
|
||||
}
|
||||
|
||||
function b() {}
|
||||
```
|
||||
|
||||
### `ignoreTypeValueShadow`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
This is generally safe because you cannot use variables in type locations without a `typeof` operator, so there's little risk of confusion.
|
||||
|
||||
Examples of **correct** code with `{ ignoreTypeValueShadow: true }`:
|
||||
|
||||
```ts option='{ "ignoreTypeValueShadow": true }' showPlaygroundButton
|
||||
type Foo = number;
|
||||
interface Bar {
|
||||
prop: number;
|
||||
}
|
||||
|
||||
function f() {
|
||||
const Foo = 1;
|
||||
const Bar = 'test';
|
||||
}
|
||||
```
|
||||
|
||||
:::note
|
||||
|
||||
_Shadowing_ specifically refers to two identical identifiers that are in different, nested scopes. This is different from _redeclaration_, which is when two identical identifiers are in the same scope. Redeclaration is covered by the [`no-redeclare`](./no-redeclare.mdx) rule instead.
|
||||
|
||||
:::
|
||||
|
||||
### `ignoreFunctionTypeParameterNameValueShadow`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
Each of a function type's arguments creates a value variable within the scope of the function type. This is done so that you can reference the type later using the `typeof` operator:
|
||||
|
||||
```ts
|
||||
type Func = (test: string) => typeof test;
|
||||
|
||||
declare const fn: Func;
|
||||
const result = fn('str'); // typeof result === string
|
||||
```
|
||||
|
||||
This means that function type arguments shadow value variable names in parent scopes:
|
||||
|
||||
```ts
|
||||
let test = 1;
|
||||
type TestType = typeof test; // === number
|
||||
type Func = (test: string) => typeof test; // this "test" references the argument, not the variable
|
||||
|
||||
declare const fn: Func;
|
||||
const result = fn('str'); // typeof result === string
|
||||
```
|
||||
|
||||
If you do not use the `typeof` operator in a function type return type position, you can safely turn this option on.
|
||||
|
||||
Examples of **correct** code with `{ ignoreFunctionTypeParameterNameValueShadow: true }`:
|
||||
|
||||
```ts option='{ "ignoreFunctionTypeParameterNameValueShadow": true }' showPlaygroundButton
|
||||
const test = 1;
|
||||
type Func = (test: string) => typeof test;
|
||||
```
|
||||
|
||||
## FAQ
|
||||
|
||||
### Why does the rule report on enum members that share the same name as a variable in a parent scope?
|
||||
|
||||
Reporting on this case isn't a bug - it is completely intentional and correct reporting! The rule reports due to a relatively unknown feature of enums - enum members create a variable within the enum scope so that they can be referenced within the enum without a qualifier.
|
||||
|
||||
To illustrate this with an example:
|
||||
|
||||
```ts
|
||||
const A = 2;
|
||||
enum Test {
|
||||
A = 1,
|
||||
B = A,
|
||||
}
|
||||
|
||||
console.log(Test.B);
|
||||
// what should be logged?
|
||||
```
|
||||
|
||||
Naively looking at the above code, it might look like the log should output `2`, because the outer variable `A`'s value is `2` - however, the code instead outputs `1`, which is the value of `Test.A`. This is because the unqualified code `B = A` is equivalent to the fully-qualified code `B = Test.A`. Due to this behavior, the enum member has **shadowed** the outer variable declaration.
|
||||
124
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-this-alias.mdx
generated
vendored
124
node_modules/@typescript-eslint/eslint-plugin/docs/rules/no-this-alias.mdx
generated
vendored
|
|
@ -1,124 +0,0 @@
|
|||
---
|
||||
description: 'Disallow aliasing `this`.'
|
||||
---
|
||||
|
||||
import Tabs from '@theme/Tabs';
|
||||
import TabItem from '@theme/TabItem';
|
||||
|
||||
> 🛑 This file is source code, not the primary documentation location! 🛑
|
||||
>
|
||||
> See **https://typescript-eslint.io/rules/no-this-alias** for documentation.
|
||||
|
||||
Assigning a variable to `this` instead of properly using arrow lambdas may be a symptom of pre-ES6 practices
|
||||
or not managing scope well.
|
||||
|
||||
## Examples
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts
|
||||
const self = this;
|
||||
|
||||
setTimeout(function () {
|
||||
self.doWork();
|
||||
});
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts
|
||||
setTimeout(() => {
|
||||
this.doWork();
|
||||
});
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## Options
|
||||
|
||||
### `allowDestructuring`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
It can sometimes be useful to destructure properties from a class instance, such as retrieving multiple properties from the instance in one of its methods.
|
||||
`allowDestructuring` allows those destructures and is `true` by default.
|
||||
You can explicitly disallow them by setting `allowDestructuring` to `false`.
|
||||
|
||||
Examples of code for the `{ "allowDestructuring": false }` option:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowDestructuring": false }'
|
||||
class ComponentLike {
|
||||
props: unknown;
|
||||
state: unknown;
|
||||
|
||||
render() {
|
||||
const { props, state } = this;
|
||||
|
||||
console.log(props);
|
||||
console.log(state);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowDestructuring": false }'
|
||||
class ComponentLike {
|
||||
props: unknown;
|
||||
state: unknown;
|
||||
|
||||
render() {
|
||||
console.log(this.props);
|
||||
console.log(this.state);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
### `allowedNames`
|
||||
|
||||
{/* insert option description */}
|
||||
|
||||
`no-this-alias` can alternately be used to allow only a specific list of names as `this` aliases.
|
||||
We recommend against this except as a transitory step towards fixing all rule violations.
|
||||
|
||||
Examples of code for the `{ "allowedNames": ["self"] }` option:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="❌ Incorrect">
|
||||
|
||||
```ts option='{ "allowedNames": ["self"] }'
|
||||
class Example {
|
||||
method() {
|
||||
const that = this;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="✅ Correct">
|
||||
|
||||
```ts option='{ "allowedNames": ["self"] }'
|
||||
class Example {
|
||||
method() {
|
||||
const self = this;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
## When Not To Use It
|
||||
|
||||
If your project is structured in a way that it needs to assign `this` to variables, this rule is likely not for you.
|
||||
If only a subset of your project assigns `this` to variables then you might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue