Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat(eslint-plugin): [no-floating-promises] add option 'allowForKnownSafePromises'#9186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
48 commits
Select commitHold shift + click to select a range
476f867
feat: [no-floating-promises] add an
arkapratimcFeb 17, 2024
7bbba26
chore: snapshot errors
arkapratimcFeb 18, 2024
38ea99f
chore: add a test
arkapratimcFeb 19, 2024
f15a0bb
chore: add another test
arkapratimcFeb 19, 2024
0019678
chore: rewrite
arkapratimcFeb 21, 2024
d231660
Merge branch 'main' into issue-7008
arkapratimcMar 19, 2024
379a2d0
chore: docs & test
arkapratimcMar 19, 2024
035484b
chore: add jsdoc comment
arkapratimcMar 19, 2024
6fe2efa
chore: cspell
arkapratimcMar 19, 2024
2269319
chore: lint
arkapratimcMar 19, 2024
2f7ed24
Merge branch 'main' into issue-7008
arkapratimcApr 4, 2024
27b463f
chore: address reviews
arkapratimcApr 4, 2024
6e221be
chore: lint errors
arkapratimcApr 4, 2024
4400e3b
chore: remove invalid js/ts code
arkapratimcApr 5, 2024
856a1a0
chore: add thenables
arkapratimcApr 5, 2024
9bd2105
Merge branch 'main' into issue-7008
arkapratimcApr 5, 2024
b7ac1fd
chore: fix failures
arkapratimcApr 5, 2024
0fbc581
chore: re-write tests
arkapratimcApr 8, 2024
c50ae5b
chore: more tests
arkapratimcApr 8, 2024
af882dd
chore: fix schemas
arkapratimcApr 8, 2024
4c51ce3
chore: typo
arkapratimcApr 8, 2024
52019b2
fix: docs
arkapratimcApr 9, 2024
e5ffd3d
chore: nits
arkapratimcApr 9, 2024
345a65d
snapshots
arkapratimcApr 9, 2024
304a53c
chore: address reviews
arkapratimcApr 24, 2024
497e8f7
chore: reduce tests
arkapratimcApr 24, 2024
842bd2d
chore: line numbers
arkapratimcApr 24, 2024
6b01c41
chore: docs
arkapratimcApr 25, 2024
f10ae89
chore: typos
arkapratimcApr 25, 2024
4a7d516
chore: address reviews
arkapratimcApr 27, 2024
aa94a28
fix: condition issues
arkapratimcApr 27, 2024
171701b
chore: update docs
arkapratimcApr 29, 2024
ecd31e3
chore: tag function
arkapratimcApr 29, 2024
a7fc9a2
chore: address reviews
arkapratimcMay 1, 2024
0ab7060
chore: revert var name
arkapratimcMay 1, 2024
441e467
chore: address reviews
arkapratimcMay 11, 2024
7422cf5
chore: lint & tests
arkapratimcMay 11, 2024
cbbda8a
chore: comments
arkapratimcMay 26, 2024
b1ce3f3
new logic
kirkwaiblingerMay 28, 2024
597f3bf
make use of closure
kirkwaiblingerMay 28, 2024
9a6ced2
rename variable
kirkwaiblingerMay 30, 2024
e0355d8
Merge branch 'main' into kirk-safe-promises
kirkwaiblingerMay 30, 2024
049230f
wording
kirkwaiblingerMay 30, 2024
963c806
whoops, copypasta mistake
kirkwaiblingerMay 30, 2024
0bdd2ef
remove test comment
kirkwaiblingerMay 31, 2024
98e3120
simplify comments
kirkwaiblingerMay 31, 2024
47b2661
remove bare string specifier
kirkwaiblingerMay 31, 2024
d391a04
docs
kirkwaiblingerMay 31, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletionspackages/eslint-plugin/docs/rules/no-floating-promises.mdx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -119,6 +119,63 @@ await (async function () {
})();
```

### `allowForKnownSafePromises`

This option allows marking specific types as "safe" to be floating. 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 an array of type specifiers to consider safe.
Each item in the array must have one of the following forms:

- A type defined in a file (`{ from: "file", name: "Foo", path: "src/foo-file.ts" }` with `path` being an optional path relative to the project root directory)
- A type from the default library (`{ from: "lib", name: "PromiseLike" }`)
- A type from a package (`{ from: "package", name: "Foo", package: "foo-lib" }`, this also works for types defined in a typings package).

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>

## When Not To Use It

This rule can be difficult to enable on large existing projects that set up many floating Promises.
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -142,11 +142,12 @@ interface Foo {

Some complex types cannot easily be made readonly, for example the `HTMLElement` type or the `JQueryStatic` type from `@types/jquery`. This option allows you to globally disable reporting of such types.

Each item must be one of:
This option takes an array of type specifiers to ignore.
Each item in the array must have one of the following forms:

- A type defined in a file (`{from: "file", name: "Foo", path: "src/foo-file.ts"}` with `path` being an optional path relative to the project root directory)
- A type from the default library (`{from: "lib", name: "Foo"}`)
- A type from a package (`{from: "package", name: "Foo", package: "foo-lib"}`, this also works for types defined in a typings package).
- A type defined in a file (`{from: "file", name: "Foo", path: "src/foo-file.ts"}` with `path` being an optional path relative to the project root directory)
- A type from the default library (`{from: "lib", name: "Foo"}`)
- A type from a package (`{from: "package", name: "Foo", package: "foo-lib"}`, this also works for types defined in a typings package).

Additionally, a type may be defined just as a simple string, which then matches the type independently of its origin.

Expand Down
118 changes: 67 additions & 51 deletionspackages/eslint-plugin/src/rules/no-floating-promises.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,17 +3,22 @@ import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';

import type { TypeOrValueSpecifier } from '../util';
import {
createRule,
getOperatorPrecedence,
getParserServices,
OperatorPrecedence,
readonlynessOptionsDefaults,
readonlynessOptionsSchema,
typeMatchesSpecifier,
} from '../util';

type Options = [
{
ignoreVoid?: boolean;
ignoreIIFE?: boolean;
allowForKnownSafePromises?: TypeOrValueSpecifier[];
},
];

Expand DownExpand Up@@ -79,6 +84,7 @@ export default createRule<Options, MessageId>({
'Whether to ignore async IIFEs (Immediately Invoked Function Expressions).',
type: 'boolean',
},
allowForKnownSafePromises: readonlynessOptionsSchema.properties.allow,
},
additionalProperties: false,
},
Expand All@@ -89,12 +95,16 @@ export default createRule<Options, MessageId>({
{
ignoreVoid: true,
ignoreIIFE: false,
allowForKnownSafePromises: readonlynessOptionsDefaults.allow,
},
],

create(context, [options]) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
// TODO: #5439
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const allowForKnownSafePromises = options.allowForKnownSafePromises!;

return {
ExpressionStatement(node): void {
Expand DownExpand Up@@ -253,11 +263,11 @@ export default createRule<Options, MessageId>({
// Check the type. At this point it can't be unhandled if it isn't a promise
// or array thereof.

if (isPromiseArray(checker,tsNode)) {
if (isPromiseArray(tsNode)) {
return { isUnhandled: true, promiseArray: true };
}

if (!isPromiseLike(checker,tsNode)) {
if (!isPromiseLike(tsNode)) {
return { isUnhandled: false };
}

Expand DownExpand Up@@ -322,63 +332,69 @@ export default createRule<Options, MessageId>({
// we just can't tell.
return { isUnhandled: false };
}
},
});

function isPromiseArray(checker: ts.TypeChecker,node: ts.Node): boolean {
const type = checker.getTypeAtLocation(node);
for (const ty of tsutils
.unionTypeParts(type)
.map(t => checker.getApparentType(t))) {
if (checker.isArrayType(ty)) {
const arrayType = checker.getTypeArguments(ty)[0];
if (isPromiseLike(checker,node, arrayType)) {
return true;
}
}
function isPromiseArray(node: ts.Node): boolean {
const type = checker.getTypeAtLocation(node);
for (const ty of tsutils
.unionTypeParts(type)
.map(t => checker.getApparentType(t))) {
if (checker.isArrayType(ty)) {
const arrayType = checker.getTypeArguments(ty)[0];
if (isPromiseLike(node, arrayType)) {
return true;
}
}

if (checker.isTupleType(ty)) {
for (const tupleElementType of checker.getTypeArguments(ty)) {
if (isPromiseLike(checker, node, tupleElementType)) {
return true;
if (checker.isTupleType(ty)) {
for (const tupleElementType of checker.getTypeArguments(ty)) {
if (isPromiseLike(node, tupleElementType)) {
return true;
}
}
}
}
return false;
}
}
return false;
}

// Modified from tsutils.isThenable() to only consider thenables which can be
// rejected/caught via a second parameter. Original source (MIT licensed):
//
// https://github.com/ajafff/tsutils/blob/49d0d31050b44b81e918eae4fbaf1dfe7b7286af/util/type.ts#L95-L125
function isPromiseLike(
checker: ts.TypeChecker,
node: ts.Node,
type?: ts.Type,
): boolean {
type ??= checker.getTypeAtLocation(node);
for (const ty of tsutils.unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined) {
continue;
}
// Modified from tsutils.isThenable() to only consider thenables which can be
// rejected/caught via a second parameter. Original source (MIT licensed):
//
// https://github.com/ajafff/tsutils/blob/49d0d31050b44b81e918eae4fbaf1dfe7b7286af/util/type.ts#L95-L125
function isPromiseLike(node: ts.Node, type?: ts.Type): boolean {
type ??= checker.getTypeAtLocation(node);

const thenType = checker.getTypeOfSymbolAtLocation(then, node);
if (
hasMatchingSignature(
thenType,
signature =>
signature.parameters.length >= 2 &&
isFunctionParam(checker, signature.parameters[0], node) &&
isFunctionParam(checker, signature.parameters[1], node),
)
) {
return true;
// Ignore anything specified by `allowForKnownSafePromises` option.
if (
allowForKnownSafePromises.some(allowedType =>
typeMatchesSpecifier(type, allowedType, services.program),
)
) {
return false;
}

for (const ty of tsutils.unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined) {
continue;
}

const thenType = checker.getTypeOfSymbolAtLocation(then, node);
if (
hasMatchingSignature(
thenType,
signature =>
signature.parameters.length >= 2 &&
isFunctionParam(checker, signature.parameters[0], node) &&
isFunctionParam(checker, signature.parameters[1], node),
)
) {
return true;
}
}
return false;
}
}
return false;
}
},
});

function hasMatchingSignature(
type: ts.Type,
Expand Down
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp