对于这种类型的常量,我希望 Typescript 推断类型:
const foo = 'foo';
对于分配给某些函数结果的常量,我希望注释是强制性的:
const bar: number = baz();
是否有 TS 编译器选项或 TSlint 规则或 smth?
在 TypeScript 或内置的 typescript-eslint lint 规则中无法做到这一点。这在很大程度上是因为,正如@Shanon Jackson 评论的那样,编写不必要的变量注释通常不是最佳实践。
plugin:@typescript-eslint/typedef
lint 规则 可以在变量和/或其他构造中强制执行类型注释。但它无法配置为执行此问题所需的操作。它的文档还强烈建议使用 TypeScript 的 --noImplicitAny
和 --strictPropertyInitialization
。
如果您真的想这样做,您可以使用 typescript-eslint 编写自定义规则。或者,对于更少的代码,您可以使用 ESLint 的
no-restricted-syntax
规则 来禁止 变量声明符,其 id 没有 类型注释 并且其 初始值 属于 调用表达式 类型:
{
"rules": {
"no-restricted-syntax": [
"error",
{
"message": "My preference is type annotations on variables initialized to function call results",
"selector": "VariableDeclarator:not([id.typeAnnotation])[init.type=CallExpression]"
}
]
}
}