【问题标题】:How to make typescript strict option work completely?如何使打字稿严格选项完全工作?
【发布时间】:2020-05-31 04:21:13
【问题描述】:

我已强制执行严格选项,但 typescript 仍然没有抱怨未在 sn-p 中定义 port、req、res 的类型。我正在使用 Vscode 以及如何完全执行它。

import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('Hello !');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "strict": true,    
  "lib": ["es2015"],
  "--isolatedModules":true,
}

【问题讨论】:

    标签: typescript visual-studio express typescript-typings


    【解决方案1】:

    tsc 的 --strict compiler option 是一堆单独编译器选项的简写,这些选项都不需要您在任何地方注释变量/参数。编译器非常乐意为未注释的变量和参数推断类型,并且大多数时候这是首选约定。 --strict 真正抱怨缺少注释的唯一一次是编译器无法为其推断出好的类型并回退到使用any。但这只是 --noImplicitAny 试图避免您意外使用不安全的 any 类型,而不是试图提醒您注释所有内容。

    在上面的代码中,未注释的app 常量被推断为Express 类型; port 被推断为3000 类型,而reqres 被推断为RequestResponse 类型,就好像你自己这样注释它们:

    import express, { Express, Request, Response } from 'express';
    const app: Express = express();
    const port: 3000 = 3000;
    app.get('/', (req: Request, res: Response) => {
      res.send('Hello !');
    });
    

    编译器唯一不满意的地方是Function 类型的回调app.listen(),其中err 参数没有上下文类型,编译器选择any。所以这里是唯一需要注释的地方:

    app.listen(port, (err: any) => {
      if (err) {
        return console.error(err);
      }
      return console.log(`server is listening on ${port}`);
    });
    

    话虽如此,如果您想对每个未注释的变量或参数进行投诉,您应该在 tsc 旁边使用像 TSLintESLint 这样的 linter。

    如果你使用 TSLint,你可以启用the typedef rule,它“需要类型定义存在”。有一些子选项专门针对函数参数("parameter""arrow-parameter")和变量("variable-declaration" and "variable-declaration-ignore-function")的声明。

    如果你使用 ESLint,你可以启用它的typedef rule,它“需要类型注解存在”。同样,函数参数("parameter""arrowParameter")和变量声明("variableDeclaration")也有子选项。

    其中任何一个都应该让你得到你想要的行为。但同样,传统观点认为类型推断是一件好事。正如 ESLint 的 typedef 文档所说:“如果您认为编写不必要的类型注释的成本不合理,则不要使用此规则。”


    好的,希望对您有所帮助;祝你好运!

    Playground link to code

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2014-05-04
      • 1970-01-01
      相关资源
      最近更新 更多