xFilipe xFilipe - 5 months ago 18
JSON Question

Typescript compiling even with an error, TS2304

I'm doing some tests with Typescript and even when I force an error the code is compiled to javascript. I'm using vscode tasks to compile.

app.ts

function getAllBooks() {
let books = [
{ title: "book1", author: "author1", available: true },
{ title: "book2", author: "author2", available: false },
{ title: "book3", author: "author3", available: true }
];

return books;
}


function logFirstAvailable(books) {
let numberOfBooks = books.length;

for (let book of books) {
let firstAvailable = "";

if (book.available) {
firstAvailable = book.title;
break;
}
}

console.log('Total books: ' + numberOfBooks);
console.log('First Available: ' + firstAvailable); // error TS2304: Cannot find name 'firstAvailable'.
}

const ALL_BOOKS = getAllBooks();
logFirstAvailable(ALL_BOOKS);


app.js

function getAllBooks() {
var books = [
{ title: "book1", author: "author1", available: true },
{ title: "book2", author: "author2", available: false },
{ title: "book3", author: "author3", available: true }
];
return books;
}
function logFirstAvailable(books) {
var numberOfBooks = books.length;
for (var _i = 0, books_1 = books; _i < books_1.length; _i++) {
var book = books_1[_i];
var firstAvailable = "";
if (book.available) {
firstAvailable = book.title;
break;
}
}
console.log('Total books: ' + numberOfBooks);
console.log('First Available: ' + firstAvailable);
}
var ALL_BOOKS = getAllBooks();
logFirstAvailable(ALL_BOOKS);
//# sourceMappingURL=app.js.map


tasks.json

{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": [
"--target", "ES5",
"--outdir", "js",
"--sourceMap",
"--watch",
"app.ts"
],
"showOutput": "silent",
"problemMatcher": "$tsc"
}


tsconfig.json

{
"compilerOptions": {
"module": "commonjs"
}
}


If this is a normal behavior, how to block typescript to compile if any errors occurs?

Answer

Have you tried --noEmitOnError? Reading the args listed under tsc --help sounds like just the ticket.

{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "args": [
        "--target", "ES5",
        "--outdir", "js",
        "--sourceMap",
        "--noEmitOnError",
        "--watch",
        "app.ts"
    ],
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}