Skip to content
← Back to rules

typescript/no-unsafe-assignment Pedantic

💭 This rule requires type information.

它的作用

此规则不允许将类型为 any 的值赋给变量和属性。

为什么这很糟糕?

TypeScript 中的 any 类型会禁用类型检查,并且可能导致运行时错误。当你将一个 any 值赋给一个有类型的变量时,本质上是在绕过 TypeScript 的类型安全,而对实际值没有任何保证。

示例

以下是此规则的错误代码示例:

ts
declare const anyValue: any;

const str: string = anyValue; // 不安全的赋值

let num: number;
num = anyValue; // 不安全的赋值

const obj = {
  prop: anyValue as any, // 不安全的赋值
};

interface User {
  name: string;
  age: number;
}

const user: User = anyValue; // 不安全的赋值

以下是此规则的正确代码示例:

ts
declare const stringValue: string;
declare const numberValue: number;
declare const unknownValue: unknown;

const str: string = stringValue; // 安全

let num: number;
num = numberValue; // 安全

// 对 unknown 使用类型守卫
if (typeof unknownValue === "string") {
  const str2: string = unknownValue; // 类型守卫之后安全
}

// 显式 any 赋值(仍不推荐,但这是有意为之)
const anything: any = unknownValue;

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/no-unsafe-assignment": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/no-unsafe-assignment": "error",
  },
});
bash
oxlint --type-aware --deny typescript/no-unsafe-assignment

版本

此规则添加于 v1.12.0。

参考资料