6

I want to check typescript type before commit, So i use tsc --noEmit $(changedFile). However, This command can not specify config file.

I found --project option, But this option will check entire project and i just want to check changedFile, Because some old files has type error but do not need to handle.

So how can i only check changedFile type before commit ?

Liam
  • 27,717
  • 28
  • 128
  • 190
Mebtte
  • 129
  • 1
  • 8

4 Answers4

13

You can use an awesome tool called lint-staged.
This library lint your files before each commit. https://github.com/okonet/lint-staged

Installation

npx mrm lint-staged

Usage for TypeScript

// lint-staged.config.js
module.exports = {
  '**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit'
}
David Leuliette
  • 1,595
  • 18
  • 26
5

I had the same problem and this package helped me for checking types in the lint-staged:

"**/*.ts?(x)": [
  "tsc-files --noEmit"
]

you can install tsc-files package with npm i tsc-files

Reza Hasani
  • 61
  • 1
  • 1
0

you might want to use a pre-commit hook (https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks).

It it, you can get the files about to be commited with git diff --staged --name-only you could then run your tsc --noEmit $(changedFile).

padawin
  • 4,230
  • 15
  • 19
-1

tsc doesn't provide a direct way to process specified files with the project settings (if you pass files to tsc, it ignores the config file), but it does allow you to extend a config file and override its list of included files, e.g.:

$ cat ./tsconfig-temp.json
{
    "extends": "./tsconfig.json",
    "include": ["./temp.ts"]
}

A wrapper script can be used to generate a config file like this on the fly with the specified file(s), e.g. (using jo to create the JSON):

$ cat tsc-files.sh
#!/usr/bin/bash

TEMP='./tsconfig-temp.json'
trap 'rm "$TEMP"' EXIT

jo extends=./tsconfig.json include=$(jo -a "$@") > $TEMP \
    && tsc --noEmit --project "$TEMP"

usage

$ tsc-files.sh ./temp.ts

Alternatively, you can use the tsc-files package on npm, which does this for you:

usage

$ tsc-files --noEmit ./temp.ts
chocolateboy
  • 1,693
  • 1
  • 19
  • 21