typescript/restrict-template-expressions 正确性
它的作用
此规则限制模板字面量表达式中允许的类型。
为什么这是不好的?
模板字面量会对插入的值调用 toString()。某些类型没有有意义的字符串表示形式(例如对象会变成 "[object Object]"),或者可能根本不存在 toString 方法。此规则有助于确保仅在模板表达式中使用适当的类型。
示例
以下为该规则的 错误 代码示例:
declare const obj: object;
declare const sym: symbol;
declare const fn: () => void;
declare const arr: unknown[];
// 对象会变成 "[object Object]"
const str1 = `Value: ${obj}`;
// 符号的输出可能不符合预期
const str2 = `Symbol: ${sym}`;
// 函数会变成其源码或 "[Function]"
const str3 = `Function: ${fn}`;
// 数组的格式可能不符合预期
const str4 = `Array: ${arr}`;
// undefined/null 会变成 "undefined"/"null",这可能会引起混淆
declare const maybeValue: string | undefined;
const str5 = `Value: ${maybeValue}`; // 可能是 "Value: undefined"以下为该规则的 正确 代码示例:
declare const str: string;
declare const num: number;
declare const bool: boolean;
declare const obj: object;
// 安全的类型
const result1 = `String: ${str}`;
const result2 = `Number: ${num}`;
const result3 = `Boolean: ${bool}`;
// 复杂类型的显式转换
const result4 = `Object: ${JSON.stringify(obj)}`;
const result5 = `Array: ${arr.join(", ")}`;
// 显式处理 undefined/null
declare const maybeValue: string | undefined;
const result6 = `Value: ${maybeValue ?? "N/A"}`;
const result7 = `Value: ${maybeValue || "default"}`;
// 未知值的类型守卫
declare const unknown: unknown;
const result8 = typeof unknown === "string" ? `Value: ${unknown}` : "Invalid";配置
此规则接受一个配置对象,包含以下属性:
allow
type: array
default: [{"from":"lib", "name":["Error", "URL", "URLSearchParams"]}]
允许在模板表达式中使用的额外类型的数组。默认包括来自 lib 的 Error、URL 和 URLSearchParams。
allow[n]
type: string
用于匹配特定声明的类型或值规范
支持四种类型的规范:
- 字符串规范(已弃用):按名称进行全局匹配
"Promise"- 文件规范:匹配在本地文件中声明的类型/值
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- Lib 规范:匹配 TypeScript 内置 lib 类型
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- 包规范:匹配来自 npm 包的类型/值
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }allowAny
type: boolean
default: true
是否允许在模板表达式中使用 any 类型的值。
allowArray
type: boolean
default: false
是否允许在模板表达式中使用数组类型。
allowBoolean
type: boolean
default: true
是否允许在模板表达式中使用布尔类型。
allowNever
type: boolean
default: false
是否允许在模板表达式中使用 never 类型。
allowNullish
type: boolean
default: true
是否允许在模板表达式中使用空值类型(null 或 undefined)。
allowNumber
type: boolean
default: true
是否允许在模板表达式中使用数字和 bigint 类型。
allowRegExp
type: boolean
default: true
是否允许在模板表达式中使用 RegExp 值。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
{
"rules": {
"typescript/restrict-template-expressions": "error"
}
}oxlint --type-aware --deny typescript/restrict-template-expressions