16

Take the following Typescript arrow function:

/**
 * 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)
}

When Typescript is configured in tsconfig.json as such:

"noImplicitAny": true,

This correctly results in a compilation error:

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

Visual Studio Code is also smart enough to inform you about this issue during development.

My goal is to create a precommit git hook that prevents such errors from ending up in version control. I tried to do this with tslint, husky and lint-staged using this npm script:

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

However, this does not result in the compilation error showing up by tslint. It is silently ignored.

I then tried to add a rule in tslint.json:

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

While this did make tslint complain, it also started to complain in anonymous arrow functions where the tsc compiler does not complain. In these arrow functions it should not be necessary to add types because the types were already set previously in the parent scope (they are inferred).

So basically, I would like for tslint to behave the same as tsc in this case. Anytime there is an error that would cause compilation to fail (such as the above arrow function), I would like to prevent the commit, but without actually compiling to Javascript. Is this possible?

4

2 回答 2

11

我认为你最好的选择是运行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 错误必要的黑客攻击(只要您标记它们以便以后可以搜索它们),然后将您的钩子设置为在整个项目中没有错误。事实上,noImplicitAny特别是关于几年前我将一个 JavaScript 项目迁移到 TypeScript 时,我写了一个脚本,any在有隐式any错误的地方插入了一个显式的脚本,然后我在闲暇时修复了显式any的 s。如果你有兴趣,我可以分享脚本。

于 2018-07-26T04:49:28.007 回答
2

我没有足够的声誉将其添加为评论,但是任何遇到类似错误的人

./scripts/ts-staged-files.sh: line 4: 
   src/ui/Components/Select/Select.tsx: division by 0 
  (error token is "/Components/Select/Select.tsx")

我对 Matt McCutchen 的回答做了这个小修改来修复它。

#!/bin/bash

include_files=()

for f in "$@"; do
  include_files+=("${f#$PWD/}")
done
于 2018-12-01T20:47:23.690 回答