TypeScript是否有类似C++[[nodiscard]]的返回值强制使用指定符?
TypeScript中实现类似C++ [[nodiscard]]的效果
TypeScript本身没有内置的类似C++ [[nodiscard]]的属性,但可以通过ESLint的规则配置来实现相同需求——强制函数返回值必须被使用,否则触发错误或警告。
实现步骤
安装依赖
确保项目中已安装ESLint及TypeScript相关插件:npm install eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev配置ESLint规则
在项目的ESLint配置文件(如.eslintrc.js)中添加以下规则:module.exports = { parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], rules: { '@typescript-eslint/no-unused-expressions': [ 'error', // 可改为'warn'触发警告 { allowShortCircuit: false, allowTernary: false, allowTaggedTemplates: false, enforceForJSX: false } ] } };
效果验证
以你的示例代码为例:
class MyClass { value: number; constructor() { this.value = 0; } } function setSomeFields(someThing: MyClass) { const other = new MyClass(); other.value = someThing.value; return other; } const myClass = new MyClass(); // ❌ 会触发ESLint错误 setSomeFields(myClass); // ✅ 正确用法:接收返回值 const newMyClass = setSomeFields(myClass);
配置完成后,直接调用setSomeFields(myClass)而不接收返回值时,ESLint会抛出错误提示:"Expected an assignment or function call and instead saw an expression."
补充说明
- 若仅需警告而非错误,可将规则中的
'error'改为'warn'。 - 该规则会检查所有返回类型非
void/undefined的函数调用,确保返回值被合理使用(赋值给变量、作为参数传递等)。
内容的提问来源于stack exchange,提问作者cLepz
相关产品推荐
相关产品推荐

