English

TypeScriptで宣言前に変数を使うと出るTS2448の直し方

​​TypeScript​トラブルシュート

error TS2448: Block-scoped variable 'count' used before its declaration. は、let や const で宣言した変数を、宣言の行より上で使ったときに出るエラーです。宣言を使う場所より上に移すか、関数なら function 宣言に書き換えると消えます。

ファイルの上のほうで呼んでいる処理を、const のアロー関数で下に書いたときや、オブジェクトの初期化の中で自分自身を参照したときにも出ます。どれも検証環境でエラーを起こしてから直し、tsc のエラーが消えることを確かめました。

補足

検証環境は Ubuntu 24.04、Node.js 22.23.5、npm 10.9.9、TypeScript 7.0.2 です。エディターの画面や、TypeScript 7 より前のバージョンは試していません。

let の変数で TS2448 を起こす

空のフォルダーで npm init -y を実行し、npm install -D typescript@7.0.2 で TypeScript を入れました。tsconfig.json は次の内容です。

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

src/let-ng.ts に、count を宣言より前に表示するコードを書きました。

ts
console.log(count);

let count = 1;

npx tsc を実行すると、同じ場所にエラーが2件出て、終了コードは 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 は「ブロックスコープの変数 count を、宣言より前に使っています」という意味です。もう1件の TS2454 は「count に値が入る前に使っています」という意味で、原因は同じです。--pretty を付けると、宣言がどこにあるかも示されます(検証では、文字の色を付ける制御文字を sed で取り除いて記録しました)。

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

宣言を、使う場所より上に移す

いちばん素直な直し方は、宣言の行を、使う行より上に移すことです。

ts
let count = 1;

console.log(count);

npx tsc は何も出力せずに終了コード 0 になり、TS2448 も TS2454 も消えました。JavaScript を出力して Node.js で実行すると、1 が表示されました。

型チェックを黙らせても、実行時に ReferenceError になる

TS2448 は、実行すると失敗するコードを前もって止めているエラーです。TypeScript ハンドブックの変数宣言の説明には、let などのブロックスコープの変数は宣言より前に読み書きできず、宣言までの範囲を temporal dead zone(TDZ)と呼ぶ、と書かれています。

これを確かめるため、// @ts-expect-error でエラーを黙らせた src/runtime.ts を用意しました。例外が出たら、その内容を表示します。

ts
try {
  // @ts-expect-error 宣言より前に使っている
  console.log(count);
} catch (e) {
  console.log(String(e));
}

let count = 1;

npx tsc は終了コード 0 でした。tsconfig.json は noEmit: true なので、--noEmit false を付けて上書きし、JavaScript を out/ に出力してから実行しました(検証では、出力のコマンドに && cat out/runtime.js をつないで、出力した JavaScript も表示しています)。

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

MDN の let の説明(一時的なデッドゾーン)にあるとおり、TDZ の中で変数にアクセスすると ReferenceError になります。@ts-expect-error で黙らせるのは直し方になりません。

const のアロー関数は、function 宣言にすると前から呼べる

関数を const とアロー関数で作り、ファイルの上のほうで呼んだときも 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.

呼び出しの順番を変えたくないときは、function 宣言に書き換えます。

ts
greet("たま");

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

npx tsc は終了コード 0 になり、実行すると こんにちは、たま と表示されました。MDN の function 宣言の説明にあるとおり、関数宣言はスコープの先頭に巻き上げられ、宣言より前で使えます。const に入れた関数式は巻き上げられないので、宣言を上に移すか、function 宣言にするかのどちらかです。

初期化の中で自分自身を参照している

宣言の行の中で、その変数自身を使っても 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.

TS2448 と一緒に、TS7022(「型注釈がなく、自分自身の初期化の中で参照しているので、暗黙に any 型になります」)も出ました。total の初期値を、別の変数から作るように書き直します。

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

console.log(total);

npx tsc は終了コード 0 になり、TS2448 も TS7022 も消えました。実行すると 2 と表示されました。

設定のオブジェクトで、前のプロパティの値を使って次のプロパティを作ろうとしたときも、同じ形になります(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.

オブジェクトリテラルの { ... } が終わるまで、config にはまだ値が入っていません。使い回したい値を、先に別の変数にします。

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

console.log(config.apiUrl);

npx tsc は終了コード 0 になり、実行すると https://example.com/api と表示されました。

関数の中から参照するだけなら、エラーにならない

宣言より上に書いたコードでも、関数の中から参照するだけなら TS2448 は出ません(src/deferred-ok.ts)。

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

const limit = 10;
showLimit();

npx tsc は終了コード 0 で、実行すると 10 と表示されました。関数の中身が動くのは showLimit() を呼んだときで、そのときには limit の宣言が済んでいるからです。

ただし、呼ぶ順番を逆にしても、tsc はエラーにしませんでした(src/deferred-trap.ts)。

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

showLimit();
const limit = 10;

npx tsc は終了コード 0 でしたが、出力した JavaScript を実行すると ReferenceError で止まりました。次の出力では、コマンドは実行の部分だけを、出力はエラーの1行だけを抜き出しています。

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

TypeScript ハンドブックの変数宣言の説明にも、宣言より前に書いた関数の中から変数を参照すること自体はでき、宣言より前にその関数を呼ぶのは誤りだが、TypeScript はエラーにしない、と書かれています。TS2448 が出ないからといって、呼ぶ順番まで安全とは限りません。

注意

TS2448 を消すために、関数の中に処理を移すだけでは足りません。関数を呼ぶのが変数の宣言より後になっているかを、自分で確かめます。

class と enum は番号が違う

class や enum を宣言より前に使ったときは、文面の似た別の番号のエラーになりました。src/class-ng.ts では、1行目で Cat のインスタンスを作り、その下で class Cat を宣言しています。

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.

src/enum-ng.ts では、1行目の const color = Color.Red; のあとで enum Color を宣言しています。

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

どちらも、class Cat や enum Color の宣言を、それを使う行より上に移すと、npx tsc の終了コードが 0 になりました。MDN の let の説明にあるとおり、class の宣言にも let と同じ TDZ があるので、function 宣言のように前から使うことはできません。

var に変えて消すのはやめる

let を var に変えると TS2448 は出なくなりますが、TS2454 は残りました(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.

型チェックを飛ばす --noCheck を付けて JavaScript を出力し、実行すると、エラーにはならず 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

MDN の let の説明にも、var の変数は宣言より前にアクセスすると undefined を返すと書かれています。例外で止まらず、値のないまま処理が進むので、var に変えるのは直し方になりません。宣言の順番を入れ替えます。

​Posted by 86