Skip to main content

no-unsafe-member-access

禁止访问具有 any 类型的值的成员.

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

TypeScript 中的 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.

尽管你有最好的意图,但 any 类型有时会泄漏到你的代码库中。访问 any 类型值的成员会在你的代码库中产生潜在的类型安全漏洞和错误源。

¥Despite your best intentions, the any type can sometimes leak into your codebase. Accessing a member of an any-typed value creates a potential type safety hole and source of bugs in your codebase.

此规则不允许对任何类型为 any 的变量进行成员访问。

¥This rule disallows member access on any variable that is typed as any.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-member-access": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

declare const anyVar: any;
declare const nestedAny: { prop: any };

anyVar.a;
anyVar.a.b;
anyVar['a'];
anyVar['a']['b'];

nestedAny.prop.a;
nestedAny.prop['a'];

const key = 'a';
nestedAny.prop[key];

// Using an any to access a member is unsafe
const arr = [1, 2, 3];
arr[anyVar];
nestedAny[anyVar];
Open in Playground

选项

该规则接受以下选项:

type Options = [
{
/** 是否允许在 `any` 值上使用 `?.` 可选链。 */
allowOptionalChaining?: boolean;
},
];

const defaultOptions: Options = [{ allowOptionalChaining: false }];

¥Options

allowOptionalChaining

是否允许在 any 值上使用 ?. 可选链。 Default: false.

带有 { allowOptionalChaining: true } 的此规则的代码示例:

¥Examples of code for this rule with { allowOptionalChaining: true }:

declare const outer: any;

outer.inner;
outer.middle.inner;
Open in Playground
提醒

我们仅建议使用 allowOptionalChaining 来帮助现有项目过渡到完全启用 no-unsafe-member-access。可选链接比普通属性访问更安全,因为如果父级值为 nullundefined,则不会出现运行时错误。但是,它仍然会生成一个 any 类型的值,这是不安全的。

¥We only recommend using allowOptionalChaining to help transition an existing project towards fully enabling no-unsafe-member-access. Optional chaining makes it safer than normal property accesses in that you won't get a runtime error if the parent value is null or undefined. However, it still results in an any-typed value, which is unsafe.

何时不使用它

¥When Not To Use It

如果你的代码库有许多现有的 any 或不安全代码区域,则可能很难启用此规则。在项目不安全区域中增加类型安全性时,跳过 no-unsafe-* 规则可能会更容易。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥If your codebase has many existing anys or areas of unsafe code, it may be difficult to enable this rule. It may be easier to skip the no-unsafe-* rules pending increasing type safety in unsafe areas of your project. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

相关

¥Related To


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

资源