如何配置TypeScript,在推断函数返回值为any时触发警告/错误?
如何让TypeScript在推断函数返回类型为
any时触发警告或错误? 可以通过TypeScript的编译配置实现这个需求,核心是启用noImplicitAny选项——它会在TypeScript无法推断出明确类型、只能隐式使用any时抛出错误,其中就包括函数返回类型的隐式any场景。
具体配置步骤
- 修改项目根目录下的
tsconfig.json文件,在compilerOptions中添加或启用noImplicitAny:
若需要更全面的严格类型检查,直接启用{ "compilerOptions": { "noImplicitAny": true, "strictNullChecks": true, // 可选但推荐,提升类型推断准确性 "target": "ESNext", // 根据项目需求调整 "module": "ESNext" } }strict: true即可——它包含noImplicitAny及其他多项严格规则,能最大程度避免any类型的隐式出现:{ "compilerOptions": { "strict": true, // 其他项目配置 } }
效果验证
针对你给出的示例代码:
export default class MyClass { #myMethod = (e: any) => { return e && e.target && e.target.hasName("stage"); }; }
启用noImplicitAny后,TypeScript会抛出错误:Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.,直接标记出返回类型隐式为any的函数。
例外场景处理
如果某些场景下确实需要返回any类型,可以显式标注返回类型,这样就不会触发错误:
#myMethod = (e: any): any => { return e && e.target && e.target.hasName("stage"); };
内容的提问来源于stack exchange,提问作者Jez
相关产品推荐
相关产品推荐

