typescript - 如何检查 Typescript 编译问题?

标签 typescript tslint pre-commit-hook husky lint-staged

采用以下 Typescript 箭头函数:

/**
 * Returns a probably unique component name.
 * 
 * @param baseName a suggested name to make unique.
 * @returns a probably unique name.
 */
export const getUniqueComponentName = (
  baseName
): string => {
  return baseName + Math.round(Math.random() * 10000000)
}

当 Typescript 在 tsconfig.json 中这样配置时:

"noImplicitAny": true,

这会正确地导致编译错误:

[ts] Parameter 'baseName' implicitly has an 'any' type.

Visual Studio Code 也足够智能,可以在开发过程中通知您这个问题。

我的目标是创建一个预提交 git 钩子(Hook),以防止此类错误最终出现在版本控制中。我尝试通过 tslinthuskylint-staged 使用此 npm 脚本 执行此操作:

"lint": "tslint --project tsconfig.json --config tslint.json"

但是,这不会导致 tslint 显示编译错误。它被默默地忽略了。

然后我尝试在 tslint.json 中添加一条规则:

"typedef": [
      true,
      "arrow-parameter"
    ]

虽然这确实让 tslint 提示,但它也开始在 tsc 编译器不提示的匿名箭头函数中提示。在这些箭头函数中,没有必要添加类型,因为这些类型之前已经在父作用域中设置(它们是推断的)。

基本上,在这种情况下,我希望 tslint 的行为与 tsc 相同。任何时候有一个错误会导致编译失败(比如上面的箭头函数),我想阻止提交,但实际上并没有编译成 Javascript。这可能吗?

最佳答案

我认为最好的办法是运行 tsc --noEmit -p . 并过滤修改文件中错误的输出。例如,我将以下脚本保存到 tsc-some-files:

#!/bin/bash
declare -A include_files
for f in "$@"; do
  include_files["${f#$PWD/}"]=1
done
node_modules/.bin/tsc --noEmit -p . | (
  status=0
  show_continuation=false
  while IFS='' read -r line; do
    case "$line" in
    (' '*)
      if $show_continuation; then
        echo "$line" >&2
      fi
      ;;
    (*)
      file="${line%%(*}"
      if [ -n "${include_files["$file"]}" ]; then
        show_continuation=true
        echo "$line" >&2
        status=1
      else
        show_continuation=false
      fi
      ;;
    esac
  done
  exit $status
)

并将 ./tsc-some-files 设置为我的 lint-staged 命令,它似乎有效。 (如果需要,可以使用 bash 以外的编程语言编写此代码,留给读者作为练习。)

请记住,虽然编辑一个文件可能会在另一个文件中引入错误(例如,如果您更改了另一个文件正在使用的内容的类型),所以我敦促您让您的项目清除 TypeScript 错误尽快通过任何必要的黑客攻击(只要你标记它们以便以后可以搜索它们)然后设置你的钩子(Hook)以要求整个项目中没有错误。事实上,特别是关于 noImplicitAny,当我几年前将一个 JavaScript 项目迁移到 TypeScript 时,我编写了一个脚本,在任何有隐式的地方插入一个显式的 any any 错误,然后我在闲暇时修复了明确的 any。如果您有兴趣,我可以分享脚本。

关于typescript - 如何检查 Typescript 编译问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51428789/

相关文章:

javascript - 在 Atom 编辑器中查找 TypeScript 版本,并根据需要更新 TypeScript

git - 测试将要在预提交 Hook 中提交的内容

python - 将 STDIN 传递给一个本身被传递给 Python 解释器的脚本?

git - 如何使用 husky 检查 git commit 消息格式?

javascript - 如何在 redux-toolkit 中输入 'prepare' 函数

typescript - react 表 typescript "Type is not assignable"

typescript - Typescript 中引号的使用标准是什么?

typescript - Vue Prop 没有初始化器,在构造函数中没有明确赋值

javascript - 如何在 TSLint 中对 js 和 ts 使用相同的规则