typescript/non-nullable-type-assertion-style 限制
作用
此规则优先使用非空断言,而不是对不可为空类型显式进行类型转换。
为什么这不好?
当你知道某个值不可能是 null 或 undefined 时,你可以使用非空断言(!)或类型断言(as Type)。非空断言更加简洁,并且能清楚地表达你在断言该值不是 null/undefined 的意图。
示例
此规则的错误代码示例:
ts
declare const value: string | null;
// 当非空断言更清晰时使用了类型断言
const result1 = value as string;
declare const maybe: number | undefined;
const result2 = maybe as number;
// 在函数调用中
function takesString(s: string) {
console.log(s);
}
takesString(value as string);此规则的正确代码示例:
ts
declare const value: string | null;
// 对不可为空类型使用非空断言
const result1 = value!;
declare const maybe: number | undefined;
const result2 = maybe!;
// 在函数调用中
function takesString(s: string) {
console.log(s);
}
takesString(value!);
// 对实际类型变化使用类型断言仍然可以
declare const unknown: unknown;
const str = unknown as string; // 这是不同的类型,不只是移除 null如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/non-nullable-type-assertion-style": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/non-nullable-type-assertion-style": "error",
},
});bash
oxlint --type-aware --deny typescript/non-nullable-type-assertion-style版本
此规则已在 v1.12.0 中添加。
