Thanks to visit codestin.com
Credit goes to github.com

Skip to content

feat(eslint-plugin): [no-floating-promises] add checkThenables option #9263

New issue

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

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

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/eslint-plugin/docs/rules/no-floating-promises.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,55 @@ await Promise.all([1, 2, 3].map(async x => x + 1));

## Options

### `checkThenables`

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>

:::info
This option is enabled by default in v7 but will be turned off by default in v8.
:::

### `ignoreVoid`

This option, which is `true` by default, allows you to stop the rule reporting promises consumed with void operator.
Expand Down
45 changes: 35 additions & 10 deletions packages/eslint-plugin/src/rules/no-floating-promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
createRule,
getOperatorPrecedence,
getParserServices,
isBuiltinSymbolLike,
OperatorPrecedence,
readonlynessOptionsDefaults,
readonlynessOptionsSchema,
Expand All @@ -16,9 +17,10 @@ import {

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

Expand Down Expand Up @@ -75,6 +77,12 @@ export default createRule<Options, MessageId>({
{
type: 'object',
properties: {
allowForKnownSafePromises: readonlynessOptionsSchema.properties.allow,
checkThenables: {
description:
'Whether to check all "Thenable"s, not just the built-in Promise type.',
type: 'boolean',
},
ignoreVoid: {
description: 'Whether to ignore `void` expressions.',
type: 'boolean',
Expand All @@ -84,7 +92,6 @@ export default createRule<Options, MessageId>({
'Whether to ignore async IIFEs (Immediately Invoked Function Expressions).',
type: 'boolean',
},
allowForKnownSafePromises: readonlynessOptionsSchema.properties.allow,
},
additionalProperties: false,
},
Expand All @@ -93,15 +100,18 @@ export default createRule<Options, MessageId>({
},
defaultOptions: [
{
allowForKnownSafePromises: readonlynessOptionsDefaults.allow,
checkThenables: true,
ignoreVoid: true,
ignoreIIFE: false,
allowForKnownSafePromises: readonlynessOptionsDefaults.allow,
},
],

create(context, [options]) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
const { checkThenables } = options;

// TODO: #5439
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const allowForKnownSafePromises = options.allowForKnownSafePromises!;
Expand Down Expand Up @@ -356,14 +366,10 @@ export default createRule<Options, MessageId>({
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(node: ts.Node, type?: ts.Type): boolean {
type ??= checker.getTypeAtLocation(node);

// Ignore anything specified by `allowForKnownSafePromises` option.
// The highest priority is to allow anything allowlisted
if (
allowForKnownSafePromises.some(allowedType =>
typeMatchesSpecifier(type, allowedType, services.program),
Expand All @@ -372,7 +378,26 @@ export default createRule<Options, MessageId>({
return false;
}

for (const ty of tsutils.unionTypeParts(checker.getApparentType(type))) {
// Otherwise, we always consider the built-in Promise to be Promise-like...
const typeParts = tsutils.unionTypeParts(checker.getApparentType(type));
if (
typeParts.some(typePart =>
isBuiltinSymbolLike(services.program, typePart, 'Promise'),
)
) {
return true;
}

// ...and only check all Thenables if explicitly told to
if (!checkThenables) {
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
for (const ty of typeParts) {
const then = ty.getProperty('then');
if (then === undefined) {
continue;
Expand Down

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

84 changes: 84 additions & 0 deletions packages/eslint-plugin/tests/rules/no-floating-promises.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,41 @@ promise().then(() => {});
},
],
},
{
code: `
interface SafePromise<T> extends Promise<T> {
brand: 'safe';
}

declare const createSafePromise: () => SafePromise<string>;
createSafePromise();
`,
options: [
{
allowForKnownSafePromises: [{ from: 'file', name: 'SafePromise' }],
checkThenables: true,
},
],
},
{
code: `
declare const createPromise: () => PromiseLike<number>;
createPromise();
`,
options: [{ checkThenables: false }],
},
{
code: `
interface MyThenable {
then(onFulfilled: () => void, onRejected: () => void): MyThenable;
}

declare function createMyThenable(): MyThenable;

createMyThenable();
`,
options: [{ checkThenables: false }],
},
],

invalid: [
Expand Down Expand Up @@ -2181,5 +2216,54 @@ myTag\`abc\`;
options: [{ allowForKnownSafePromises: [{ from: 'file', name: 'Foo' }] }],
errors: [{ line: 4, messageId: 'floatingVoid' }],
},
{
code: `
declare const createPromise: () => PromiseLike<number>;
createPromise();
`,
errors: [{ line: 3, messageId: 'floatingVoid' }],
options: [{ checkThenables: true }],
},
{
code: `
interface MyThenable {
then(onFulfilled: () => void, onRejected: () => void): MyThenable;
}

declare function createMyThenable(): MyThenable;

createMyThenable();
`,
errors: [{ line: 8, messageId: 'floatingVoid' }],
options: [{ checkThenables: true }],
},
{
code: `
declare const createPromise: () => Promise<number>;
createPromise();
`,
errors: [{ line: 3, messageId: 'floatingVoid' }],
options: [{ checkThenables: false }],
},
{
code: `
class MyPromise<T> extends Promise<T> {}
declare const createMyPromise: () => MyPromise<number>;
createMyPromise();
`,
errors: [{ line: 4, messageId: 'floatingVoid' }],
options: [{ checkThenables: false }],
},
{
code: `
class MyPromise<T> extends Promise<T> {
additional: string;
}
declare const createMyPromise: () => MyPromise<number>;
createMyPromise();
`,
errors: [{ line: 6, messageId: 'floatingVoid' }],
options: [{ checkThenables: false }],
},
],
});

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

Loading