Search code examples
typescriptshellpipeio-redirectiontsc

How can I grep/pipe/redirect the output of tsc (TypeScript compiler)?


My project consists of a very simple index.ts:

const answer: 42 = 43;

If I compile it, I get an expected type error (with colors; not shown here):

$ tsc
index.ts:1:7 - error TS2322: Type '43' is not assignable to type '42'.

1 const answer: 42 = 43;
        ~~~~~~


Found 1 error.

Let's say I want to grep for type errors:

$ tsc | grep "const answer"

I get no results. And no wonder:

$ tsc | wc -l
1
$ tsc | cat
index.ts(1,7): error TS2322: Type '43' is not assignable to type '42'.

Redirecting doesn't help:

$ tsc 2>&1 | wc -l
1
$ tsc 2>&1 | cat
index.ts(1,7): error TS2322: Type '43' is not assignable to type '42'.

How can I access the complete output of tsc in the terminal?


Solution

  • Use the --pretty flag:

    $ tsc --pretty | grep "const answer"
    1 const answer: 42 = 43;
    

    (Note that "--pretty output is not meant to be parsed", so use with care.)

    It works like this:

    $ tsc --pretty false
    index.ts(1,7): error TS2322: Type '43' is not assignable to type '42'.
    $ tsc --pretty true
    index.ts:1:7 - error TS2322: Type '43' is not assignable to type '42'.
    
    1 const answer: 42 = 43;
            ~~~~~~
    
    
    Found 1 error.
    
    

    It's enabled by default, "unless piping to another program or redirecting output to a file".

    You can also specify it in your tsconfig.json:

    {
        "compilerOptions": {
            "pretty": true,
        },
    }