lhk
lhk

Reputation: 30226

typescript: how to prevent emitting code with errors?

There is a common misconception that "Typescript is a superset of Javascript".
This is not true, here are two simple examples where valid Javascript causes the Typescript compiler to report an error:

var a = { foo: 1 };
a.bar = 2; // member does not exist on a

console.log(1 == "1"); // comparison of incompatible types

In many cases where it reports an error, the Typescript compiler will still output Javascript. For the examples above, this might make sense. It can support an easier incremental migration to sound static typing.

However, there are also cases where the Typescript compiler catches errors that should be treated as errors and might cause dangerously unspecified behaviour in your Javascript program. For example, in ES6, module exports are read-only. You should not be able to write to exported members of a module. As of the time of this writing, node v13.14.0. does not enforce this.

module.ts:

export var num = 1;

// just as a reference, the proper way to access num
export const setNum = (newNum:number)=>{
    num=newNum;
}
export const getNum = ()=>num;

main.ts:

import * as mod from './mod'

console.log(mod.num); // outputs 1
mod.num=2;            // compiler error
console.log(mod.num); // outputs 2

Despite throwing an error, the compiler still transpiles to Javascript and ignores the dangerous "write to read-only".

In such a scenario, I would like to prevent the compiler from producing output. How is this possible?

Upvotes: 2

Views: 1413

Answers (1)

lhk
lhk

Reputation: 30226

The typescript compiler options make it possible to specify:

 --noEmitOnError

By default this flag is set to false. But after running into a nasty side-effect of faulty code being emitted, I will always set this to true in my tsconfig.json:

{
    "compilerOptions": {
        //...
        "strict": true,
        "noEmitOnError": true
    },
    "exclude": [
        "node_modules"
    ]
}

Upvotes: 1

Related Questions