Skip to content

docs: [no-unsafe-call] clarify that you can never safely narrow Function #10058

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
Merged
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
19 changes: 18 additions & 1 deletion packages/eslint-plugin/docs/rules/no-unsafe-call.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ Note that whereas [no-unsafe-function-type](./no-unsafe-function-type.mdx) helps
See, for example, the following code:

```ts
function unsafe(maybeFunction: unknown): string {
function callUnsafe(maybeFunction: unknown): string {
if (typeof maybeFunction === 'function') {
// TypeScript allows this, but it's completely unsound.
return maybeFunction('call', 'with', 'any', 'args');
Expand All @@ -87,6 +87,23 @@ function unsafe(maybeFunction: unknown): string {
}
```

In this sort of situation, beware that there is no way to guarantee with runtime checks that a value is safe to call.
If you _really_ want to call a value whose type you don't know, your best best is to use a `try`/`catch` and suppress any TypeScript or linter errors that get in your way.

```ts
function callSafe(maybeFunction: unknown): void {
try {
// intentionally unsound type assertion
(maybeFunction as () => unknown)();
} catch (e) {
console.error(
'Function either could not be called or threw an error when called: ',
e,
);
}
}
```

## When Not To Use It

If your codebase has many existing `any`s or areas of unsafe code, it may be difficult to enable this rule.
Expand Down
Loading