typescript/非可空类型断言风格 限制
它的作用
此规则建议在处理不可为空的类型时,优先使用非空断言(!)而非显式的类型转换。
为什么这是不好的?
当你确定某个值不可能为 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如何使用
通过配置文件或 CLI 启用此规则,可以使用以下方式:
json
{
"rules": {
"typescript/non-nullable-type-assertion-style": "error"
}
}bash
oxlint --type-aware --deny typescript/non-nullable-type-assertion-style