no-unsafe-function-type
Disallow using the unsafe built-in Function type.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/recommended"
可启用此规则。
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
TypeScript 的内置 Function
类型允许使用任意数量的参数调用并返回类型 any
。Function
还允许恰好拥有 Function
类的所有属性的类或普通对象。通常最好使用函数类型语法指定函数参数和返回类型。
¥TypeScript's built-in Function
type allows being called with any number of arguments and returns type any
.
Function
also allows classes or plain objects that happen to possess all properties of the Function
class.
It's generally better to specify function parameters and return types with the function type syntax.
"全部捕获" 函数类型包括:
¥"Catch-all" function types include:
-
() => void
:没有参数且其返回被忽略的函数¥
() => void
: a function that has no parameters and whose return is ignored -
(...args: never) => unknown
:可以分配任何函数类型但无法调用的函数的 "顶层类型"¥
(...args: never) => unknown
: a "top type" for functions that can be assigned any function type, but can't be called
此规则的代码示例:
¥Examples of code for this rule:
- ❌ Incorrect
- ✅ Correct
let noParametersOrReturn: Function;
noParametersOrReturn = () => {};
let stringToNumber: Function;
stringToNumber = (text: string) => text.length;
let identity: Function;
identity = value => value;
Open in Playgroundlet noParametersOrReturn: () => void;
noParametersOrReturn = () => {};
let stringToNumber: (text: string) => number;
stringToNumber = text => text.length;
let identity: <T>(value: T) => T;
identity = value => value;
Open in Playground- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-function-type": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-function-type": "error"
}
};
在线运行试试这个规则 ↗
选项
该规则不可配置。
何时不使用它
¥When Not To Use It
如果你的项目仍在使用 TypeScript,可能很难用更精确的函数类型完全替换所有不安全的 Function
类型。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
¥If your project is still onboarding to TypeScript, it might be difficult to fully replace all unsafe Function
types with more precise function types.
You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
相关
¥Related To
'## 资源'