日本語

Fixing TS2448 “used before its declaration” in TypeScript

​​TypeScript​Troubleshooting

error TS2448: Block-scoped variable 'count' used before its declaration. appears when you use a variable declared with let or const above the line where it is declared. Move the declaration above the first use, or rewrite a function as a function declaration, and the error goes away.

You also get this error when you call a function written as a const arrow function from higher up in the file, or when an object initializer refers to itself. In each case I reproduced the error in a test environment, fixed it, and confirmed that tsc no longer reports it.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, npm 10.9.9, and TypeScript 7.0.2. I did not test editor displays or versions of TypeScript before 7.

Triggering TS2448 with a let variable

I ran npm init -y in an empty folder and installed TypeScript with npm install -D typescript@7.0.2. The tsconfig.json was as follows.

json
{
  "compilerOptions": {
    "target": "es2023",
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "noEmit": true
  },
  "include": ["src"]
}

In src/let-ng.ts, I wrote code that prints count before it is declared.

ts
console.log(count);

let count = 1;

Running npx tsc reported two errors at the same location and exited with code 1.

console
$ npx tsc
src/let-ng.ts(1,13): error TS2448: Block-scoped variable 'count' used before its declaration.
src/let-ng.ts(1,13): error TS2454: Variable 'count' is used before being assigned.

TS2448 means "block-scoped variable count is used before its declaration." The other error, TS2454, means "count is used before a value is assigned to it." Both have the same cause. With --pretty, the output also shows where the declaration is. In my test, I removed the control characters that add color with sed before recording the output.

console
$ npx tsc --pretty
src/let-ng.ts:1:13 - error TS2448: Block-scoped variable 'count' used before its declaration.

1 console.log(count);
              ~~~~~

  src/let-ng.ts:3:5 - 'count' is declared here.
    3 let count = 1;
          ~~~~~

src/let-ng.ts:1:13 - error TS2454: Variable 'count' is used before being assigned.

1 console.log(count);
              ~~~~~


Found 2 errors in the same file, starting at: src/let-ng.ts:1

Move the declaration above its use

The simplest fix is to move the declaration above the line that uses it.

ts
let count = 1;

console.log(count);

npx tsc printed nothing and exited with code 0. Both TS2448 and TS2454 were gone. When I emitted JavaScript and ran it with Node.js, it printed 1.

Silencing the type check still gives a ReferenceError at runtime

TS2448 is an error that stops code which would fail when run. The TypeScript Handbook section on variable declarations says that block-scoped variables such as let cannot be read or written before their declaration, and it calls the range before the declaration the temporal dead zone (TDZ).

To check this, I prepared src/runtime.ts, which silences the error with // @ts-expect-error. If an exception is thrown, the code prints it.

ts
try {
  // @ts-expect-error used before its declaration
  console.log(count);
} catch (e) {
  console.log(String(e));
}

let count = 1;

npx tsc exited with code 0. Because tsconfig.json sets noEmit: true, I overrode it with --noEmit false, emitted JavaScript to out/, and ran it. (In the test, I chained && cat out/runtime.js to the emit command to show the emitted JavaScript as well.)

console
$ rm -rf out; npx tsc --noEmit false --rootDir src --outDir out
$ node out/runtime.js
ReferenceError: Cannot access 'count' before initialization

As described in MDN's explanation of let (temporal dead zone), accessing a variable inside the TDZ throws a ReferenceError. Silencing the error with @ts-expect-error is not a fix.

A const arrow function can be called from above if you use a function declaration

When I created a function with const and an arrow function, then called it higher up in the file, I also got TS2448 (src/arrow-ng.ts).

ts
greet("たま");

const greet = (name: string) => {
  console.log(`こんにちは、${name}`);
};
console
$ npx tsc
src/arrow-ng.ts(1,1): error TS2448: Block-scoped variable 'greet' used before its declaration.
src/arrow-ng.ts(1,1): error TS2454: Variable 'greet' is used before being assigned.

If you don't want to change the call order, rewrite the function as a function declaration.

ts
greet("たま");

function greet(name: string) {
  console.log(`こんにちは、${name}`);
}

npx tsc exited with code 0, and running the code printed こんにちは、たま. As described in MDN's explanation of function declarations, function declarations are hoisted to the top of their scope and can be used before the declaration. A function expression stored in a const is not hoisted, so you either move the declaration up or change it to a function declaration.

Referencing itself in its own initializer

Using a variable inside its own declaration line also causes TS2448 (src/self-ng.ts).

ts
const total = total + 1;

console.log(total);
console
$ npx tsc
src/self-ng.ts(1,7): error TS7022: 'total' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
src/self-ng.ts(1,15): error TS2448: Block-scoped variable 'total' used before its declaration.

Along with TS2448, I also got TS7022, which means "there is no type annotation, and the variable is referenced directly or indirectly in its own initializer, so it implicitly has type any." I rewrote the code so that the initial value of total comes from a different variable.

ts
const base = 1;
const total = base + 1;

console.log(total);

npx tsc exited with code 0, and both TS2448 and TS7022 were gone. Running it printed 2.

The same pattern happens when you try to build the next property of an object literal from an earlier property (src/obj-ng.ts).

ts
const config = {
  baseUrl: "https://example.com",
  apiUrl: `${config.baseUrl}/api`,
};

console.log(config.apiUrl);
console
$ npx tsc
src/obj-ng.ts(1,7): error TS7022: 'config' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
src/obj-ng.ts(3,14): error TS2448: Block-scoped variable 'config' used before its declaration.

Until the object literal { ... } finishes, config has no value yet. Put the value you want to reuse into a separate variable first.

ts
const baseUrl = "https://example.com";
const config = {
  baseUrl,
  apiUrl: `${baseUrl}/api`,
};

console.log(config.apiUrl);

npx tsc exited with code 0, and running it printed https://example.com/api.

Referencing it only inside a function is not an error

Even if the code is written above the declaration, TS2448 does not appear when the variable is only referenced from inside a function (src/deferred-ok.ts).

ts
function showLimit() {
  console.log(limit);
}

const limit = 10;
showLimit();

npx tsc exited with code 0, and running it printed 10. The body of the function runs when showLimit() is called, and by then the declaration of limit has already run.

However, when I swapped the order of the calls, tsc did not report an error (src/deferred-trap.ts).

ts
function showLimit() {
  console.log(limit);
}

showLimit();
const limit = 10;

npx tsc exited with code 0, but running the emitted JavaScript stopped with a ReferenceError. In the following output, the command shows only the run step, and the output shows only the one line of the error.

console
$ node out/deferred-trap.js
ReferenceError: Cannot access 'limit' before initialization

The TypeScript Handbook section on variable declarations also says that a function written above a declaration can refer to the variable, and that calling that function before the declaration is an error, but TypeScript does not report it. Not seeing TS2448 does not mean that the call order is safe.

Warning

Moving code into a function is not enough to get rid of TS2448. You need to check yourself that the function is called after the variable's declaration.

class and enum use different error codes

When you use a class or enum before its declaration, you get an error with a different number and similar wording. In src/class-ng.ts, line 1 creates an instance of Cat, and class Cat is declared below it.

ts
const tama = new Cat("たま");

class Cat {
  constructor(public name: string) {}
}

console.log(tama.name);
console
$ npx tsc
src/class-ng.ts(1,18): error TS2449: Class 'Cat' used before its declaration.

In src/enum-ng.ts, enum Color is declared after the line const color = Color.Red; on line 1.

console
$ npx tsc
src/enum-ng.ts(1,15): error TS2450: Enum 'Color' used before its declaration.

In both cases, moving the class Cat or enum Color declaration above the line that uses it made npx tsc exit with code 0. As described in MDN's explanation of let, class declarations have the same TDZ as let, so unlike function declarations, they cannot be used before they are declared.

Don't make it go away by changing to var

Changing let to var removed TS2448, but TS2454 remained (src/var-ng.ts).

ts
console.log(count);

var count = 1;
console
$ npx tsc
src/var-ng.ts(1,13): error TS2454: Variable 'count' is used before being assigned.

I emitted JavaScript with --noCheck, which skips the type check, and ran it. It did not throw an error. Instead it printed undefined.

console
$ rm -rf out; npx tsc --noEmit false --noCheck --rootDir src --outDir out && cat out/var-ng.js && node out/var-ng.js
"use strict";
console.log(count);
var count = 1;
undefined

As MDN's explanation of let also notes, a var variable accessed before its declaration returns undefined. Because nothing throws and the code keeps running with no value, changing to var is not a fix. Reorder the declarations instead.

​Posted by 86