I have ./src/app.ts with code
function one() {
let result;
function two() {
console.log(result);
console.log("one");
}
}
package.json
{
"name": "hello_world",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon ./src/app.ts",
"build": "tsc"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^3.1.7",
"typescript": "^5.7.2"
}}
in tsconfig.json
"noEmitOnError": true,
when i run npm run build
i see ./public/app.js
"use strict";
function one() {
let result;
function two() {
console.log(result);
console.log("one");
}
}
why code compiled even though result
is undefined.
but in my vscode red sviggly line for result
variable
This new behavior is actually the 1st item of the 5.7 release announcement.
Checks for Never-Initialized Variables
For a long time, TypeScript has been able to catch issues when a variable has not yet been initialized in all prior branches.
let result: number if (someCondition()) { result = doSomeWork(); } else { let temporaryWork = doSomeWork(); temporaryWork *= 2; // forgot to assign to 'result' } console.log(result); // error: Variable 'result' is used before being assigned.
Unfortunately, there are some places where this analysis doesn’t work. For example, if the variable is accessed in a separate function, the type system doesn’t know when the function will be called, and instead takes an "optimistic" view that the variable will be initialized.
function foo() { let result: number if (someCondition()) { result = doSomeWork(); } else { let temporaryWork = doSomeWork(); temporaryWork *= 2; // forgot to assign to 'result' } printResult(); function printResult() { console.log(result); // no error here. } }
While TypeScript 5.7 is still lenient on variables that have possibly been initialized, the type system is able to report errors when variables have never been initialized at all.
function foo() { let result: number // do work, but forget to assign to 'result' function printResult() { console.log(result); // error: Variable 'result' is used before being assigned. } }