no-explicit-any
禁止
any类型.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/recommended" 可启用此规则。
此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
TypeScript 中的 any 类型是来自类型系统的危险 "应急方案"。使用 any 会禁用许多类型检查规则,通常最好只作为最后的手段或在原型代码时使用。此规则报告如果私有成员从未在构造函数之外修改,则将其标记为 any。
¥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.
any 的首选替代方案包括:
¥Preferable alternatives to any include:
-
如果类型已知,则在
interface或type中描述它¥If the type is known, describing it in an
interfaceortype -
如果类型未知,则使用更安全的
unknown类型¥If the type is not known, using the safer
unknowntype
TypeScript 的
--noImplicitAny编译器选项可防止隐含的any,但不会阻止any按照此规则的方式显式使用。¥TypeScript's
--noImplicitAnycompiler option prevents an impliedany, but doesn't preventanyfrom being explicitly used the way this rule does.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/no-explicit-any": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-explicit-any": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ 错误
- ✅ 正确
const age: any = 'seventeen';
Open in Playgroundconst ages: any[] = ['seventeen'];
Open in Playgroundconst ages: Array<any> = ['seventeen'];
Open in Playgroundfunction greet(): any {}
Open in Playgroundfunction greet(): any[] {}
Open in Playgroundfunction greet(): Array<any> {}
Open in Playgroundfunction greet(): Array<Array<any>> {}
Open in Playgroundfunction greet(param: Array<any>): string {}
Open in Playgroundfunction greet(param: Array<any>): Array<any> {}
Open in Playgroundconst age: number = 17;
Open in Playgroundconst ages: number[] = [17];
Open in Playgroundconst ages: Array<number> = [17];
Open in Playgroundfunction greet(): string {}
Open in Playgroundfunction greet(): string[] {}
Open in Playgroundfunction greet(): Array<string> {}
Open in Playgroundfunction greet(): Array<Array<string>> {}
Open in Playgroundfunction greet(param: Array<string>): string {}
Open in Playgroundfunction greet(param: Array<string>): Array<string> {}
Open in Playground选项
该规则接受以下选项:
type Options = [
{
/** 是否启用自动修复,其中 `any` 类型转换为 `unknown` 类型。 */
fixToUnknown?: boolean;
/** 是否忽略其余参数数组。 */
ignoreRestArgs?: boolean;
},
];
const defaultOptions: Options = [
{ fixToUnknown: false, ignoreRestArgs: false },
];
¥Options
fixToUnknown
是否启用自动修复,其中 any 类型转换为 unknown 类型。 Default: false.
默认情况下,此规则不会提供自动 ESLint 修复:仅选择加入建议。将类型切换到 unknown 更安全,但可能会导致额外的类型错误。
¥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.
启用 { "fixToUnknown": true } 会为规则提供一个自动修复程序,以将 : any 替换为 : unknown。
¥Enabling { "fixToUnknown": true } gives the rule an auto-fixer to replace : any with : unknown.
ignoreRestArgs
是否忽略其余参数数组。 Default: false.
以下示例在 {ignoreRestArgs: false} 时不正确,但在 {ignoreRestArgs: true} 时正确。
¥The examples below are incorrect when {ignoreRestArgs: false}, but correct when {ignoreRestArgs: true}.
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;
}
Open in Playgroundany 的替代方案
¥Alternatives to any
如果你知道对象值上存在的属性,通常最好使用 interface 或 type 来描述这些属性。如果简单的对象类型不够用,你可以选择多种策略来代替 any。以下标题描述了一些更常见的策略。
¥If you do know the properties that exist on an object value, it's generally best to use an interface or type to describe those properties.
If a straightforward object type isn't sufficient, then you can choose between several strategies instead of any.
The following headings describe some of the more common strategies.
unknown
如果你不知道值的数据形状,unknown 类型比 any 更安全。与 any 类似,unknown 表示该值可能是具有任何属性的任何类型的数据。与 any 不同,unknown 不允许任意属性访问:它要求在使用前将值缩小到更具体的类型。有关 unknown 的更多信息,请参阅 TypeScript 中的 unknown 类型。
¥If you don't know the data shape of a value, the unknown type is safer than any.
Like any, unknown indicates the value might be any kind of data with any properties.
Unlike any, unknown doesn't allow arbitrary property accesses: it requires the value be narrowed to a more specific type before being used.
See The unknown type in TypeScript for more information on unknown.
索引签名
¥Index Signatures
某些对象可以使用任意键,尤其是在 Map 和 Set 之前的代码中。TypeScript 接口可以指定 "索引签名" 类型,以指示对象上允许使用任意键。
¥Some objects are used with arbitrary keys, especially in code that predates Maps and Sets.
TypeScript interfaces may be given an "index signature" to indicate arbitrary keys are allowed on objects.
例如,此类型定义了一个对象,该对象必须具有 一个值为 number 的 apple 属性,并且可以具有任何其他值为 number | undefined 的字符串键:
¥For example, this type defines an object that must have an apple property with a number value, and may have any other string keys with number | undefined values:
interface AllowsAnyStrings {
apple: number;
[i: string]: number | undefined;
}
let fruits: AllowsAnyStrings;
fruits = { apple: 0 }; // Ok
fruits.banana = 1; // Ok
fruits.cherry = undefined; // Ok
有关索引签名的更多信息,请参阅 TypeScript 索引签名究竟是什么意思?。
¥See What does a TypeScript index signature actually mean? for more information on index signatures.
联合类型
¥Union Types
某些值可以是多种类型之一。TypeScript 允许使用 "union" 类型表示这些:包含数据可能形状列表的类型。
¥Some values can be one of multiple types. TypeScript allows representing these with "union" types: types that include a list of possible shapes for data.
联合类型通常用于描述 "nullable" 值:可以是数据类型或 null 和/或 undefined 的。例如,以下 StringLike 类型描述的数据要么是 string,要么是 undefined:
¥Union types are often used to describe "nullable" values: those that can either be a data type or null and/or undefined.
For example, the following StringLike type describes data that is either a string or undefined:
type StringLike = string | undefined;
let fruit: StringLike;
fruit = 'apple'; // Ok
fruit = undefined; // Ok
有关联合类型的更多信息,请参阅 TypeScript 手册:日常类型 > 联合类型。
¥See TypeScript Handbook: Everyday Types > Union Types for more information on union types.
类型参数约束
¥Type Parameter Constraints
"通用" 类型参数通常用于表示未知类型的值。使用 any 作为类型参数约束可能很诱人,但不建议这样做。
¥"Generic" type parameters are often used to represent a value of an unknown type.
It can be tempting to use any as a type parameter constraint, but this is not recommended.
首先,extends any 本身不执行任何操作:<T extends any> 等同于 <T>。有关更多信息,请参阅 @typescript-eslint/no-unnecessary-type-constraint。
¥First, extends any on its own does nothing: <T extends any> is equivalent to <T>.
See @typescript-eslint/no-unnecessary-type-constraint for more information.
在类型参数中,通常可以使用 never 和 unknown 代替。例如,以下代码在 AnyFunction 中使用这两种类型(而不是 any)来将 Callback 约束为任何函数类型:
¥Within type parameters, never and unknown otherwise can generally be used instead.
For example, the following code uses those two types in AnyFunction instead of anys to constrain Callback to any function type:
type AnyFunction = (...args: never[]) => unknown;
function curry<Greeter extends AnyFunction>(greeter: Greeter, prefix: string) {
return (...args: Parameters<Greeter>) => `${prefix}: ${greeter(...args)}`;
}
const greet = (name: string) => `Hello, ${name}!`;
const greetWithDate = curry(greet, 'Logged: ');
greetWithDate('linter'); // => "Logged: Hello, linter!"
有关这些类型的更多信息,请参阅 何时在 TypeScript 中使用 never 和 unknown。
¥See When to use never and unknown in TypeScript for more information on those types.
何时不使用它
¥When Not To Use It
any 始终是一个危险的应急方案。只要有可能,避免它总是更安全。TypeScript 的 unknown 几乎总是比 any 更可取。
¥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.
但是,偶尔也会出现需要使用 any 的情况。最常见的:
¥However, there are occasional situations where it can be necessary to use any.
Most commonly:
-
如果你的项目尚未完全加入 TypeScript,
any可暂时用于类型尚不清楚或无法表示的地方¥If your project isn't fully onboarded to TypeScript yet,
anycan be temporarily used in places where types aren't yet known or representable -
如果外部包还没有类型,而你想要使用
any并为其添加.d.ts¥If an external package doesn't yet have typings and you want to use
anypending adding a.d.tsfor it -
你正在处理特别复杂或微妙的代码,这些代码尚无法在 TypeScript 类型系统中表示
¥You're working with particularly complex or nuanced code that can't yet be represented in the TypeScript type system
你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
¥You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
相关
¥Related To
进一步阅读
¥Further Reading
-
TypeScript
any型¥TypeScript
anytype -
TypeScript 的
unknown型¥TypeScript's
unknowntype -
TypeScript
any类型文档¥TypeScript
anytype documentation -
TypeScript
unknown型发行说明¥TypeScript
unknowntype release notes