使用@typescript-eslint/restrict-template-expressions时如何打印布尔变量及禁用单行规则
关于@typescript-eslint/restrict-template-expressions规则的问题解答
1. 正确打印布尔类型变量的方法
由于@typescript-eslint/restrict-template-expressions规则默认禁止在模板字符串中直接使用布尔类型表达式,你可以通过以下方式处理:
- 用
String()函数显式转换为字符串:const flag: boolean = true; console.log(`flag=${String(flag)}`); - 调用
toString()方法转换:const flag: boolean = true; console.log(`flag=${flag.toString()}`); - 保留普通字符串拼接写法(该写法不会触发此规则):
const flag: boolean = true; console.log("flag=" + flag);
2. 禁用该行的规则限制
你可以通过ESLint行内注释单独禁用该行的规则检查:
- 在目标行上方添加注释:
const flag: boolean = true; // eslint-disable-next-line @typescript-eslint/restrict-template-expressions console.log(`flag=${flag}`); - 或者在目标行末尾添加注释:
const flag: boolean = true; console.log(`flag=${flag}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
内容的提问来源于stack exchange,提问作者Robert La Ferla
相关产品推荐
相关产品推荐

