TypeScriptのエラーコード(TS2322など)とは、tsc が型チェックで見つけた問題の種類を表す番号で、番号ごとに原因と直し方の型(パターン)がほぼ決まっています。 たとえば TS2322 は「代入する値の型が合わない」、TS2345 は「関数に渡す引数の型が合わない」という意味です。番号から逆引きできれば、エラーの大半は数十秒で直せます。

この記事では、よく出るエラー50件を「コード・英語メッセージ・意味・よくある原因・直し方」の逆引き表にまとめました。さらに50件すべてを最小コードで再現し、TypeScript 7.0.2(2026年10月時点の npm latest)の tsc が出した出力をそのまま掲載しています。5.9.3 と出力が異なるものは注記し、strict 系オプションとエラーの対応、長いエラーメッセージの読み方、any で黙らせずに直す判断基準まで1ページで確認できます。

TypeScriptエラーコードの逆引き早見表(50件)

検証環境:TypeScript 7.0.2 と 5.9.3(npm)、Node.js 22、--strict --target es2022 --lib es2022,dom --module esnext --moduleResolution bundler --noEmit --pretty false。追加のオプションが必要なものは「条件」に書いています。

コード 英語メッセージ(要旨) 意味 よくある原因 直し方
TS2322 Type 'X' is not assignable to type 'Y' 代入先の型に合わない 文字列を number 変数へ代入、戻り値の型違い 値を変換(Number())するか型注釈を見直す
TS2345 Argument of type 'X' is not assignable to parameter of type 'Y' 引数の型が合わない フォーム値(string)をそのまま渡す 呼び出し側で変換・絞り込み
TS2339 Property 'x' does not exist on type 'Y' そのプロパティは型にない 型定義の不足、union の片側にしかない 型に追加、in で絞り込み
TS2551 Property 'x' does not exist… Did you mean 'y'? 似た名前のつづり違い lenght などのタイプミス 提案された名前に直す
TS2304 Cannot find name 'x' 名前が見つからない import 忘れ、宣言前、型定義の未導入 import を追加、types を確認
TS2552 Cannot find name 'x'. Did you mean 'y'? 変数名のつづり違い タイプミス 提案された名前に直す
TS2531 Object is possibly 'null' 式の結果が null の可能性 null を返す関数の結果に直接アクセス 変数に受けて null チェック
TS18047 'x' is possibly 'null' 変数が null の可能性 querySelector の結果を直接使う if (!el) return; で絞り込み
TS18048 'x' is possibly 'undefined' 変数が undefined の可能性 省略可能引数、配列の要素アクセス 既定値、?.、??
TS2532 Object is possibly 'undefined' 式の結果が undefined の可能性 find() の結果に直接アクセス 変数に受けてチェック
TS18046 'x' is of type 'unknown' unknown のまま使った JSON.parse、catch (e) の e 型ガードで絞り込む
TS2454 Variable 'x' is used before being assigned 代入前に使用 宣言だけして分岐内でしか代入しない 初期値を入れる、全分岐で代入
TS7006 Parameter 'x' implicitly has an 'any' type 引数の型が推論できない 引数に型注釈がない 引数に型を書く
TS7031 Binding element 'x' implicitly has an 'any' type 分割代入の要素が any function f({ id }) に型がない ({ id }: { id: number })
TS2683 'this' implicitly has type 'any' this の型が不明 通常関数内の this 第1引数 this: T を書く、アロー関数・クラスへ
TS7053 Element implicitly has an 'any' type because expression of type 'string' can't be used to index string でオブジェクトを引けない obj[key] の key が string key を keyof typeof obj にする
TS2307 Cannot find module 'x' or its corresponding type declarations モジュールが見つからない パス違い、未インストール パス・インストール・moduleResolution を確認
TS2305 Module 'x' has no exported member 'y' その名前は export されていない 名前違い、バージョン違い export 名を確認
TS2614 …Did you mean to use 'import x from "y"' instead? default export を名前付きで import export default との取り違え import X from に直す
TS2835 Relative import paths need explicit file extensions… 相対 import に拡張子が必要 module: nodenext で ./a と書いた ./a.js と書く
TS7016 Could not find a declaration file for module 'x' 型定義がない JS だけのパッケージ @types/x を入れる、.d.ts を書く
TS2742 The inferred type of 'x' cannot be named… 推論型を d.ts に書けない 依存の奥にある型が戻り値に出る 型注釈を明示(7.0では TS2883)
TS2554 Expected N arguments, but got M 引数の数が違う 余分・不足の引数 定義に合わせる、省略可能にする
TS2556 A spread argument must either have a tuple type… 配列を固定長引数に展開 number[] を f(...arr) as const かタプル型にする
TS2794 Expected 1 arguments, but got 0. Did you forget to include 'void'…? Promise の resolve に値がない new Promise((r) => r()) new Promise<void>
TS2769 No overload matches this call どのオーバーロードにも合わない 引数の型がすべての候補と不一致 候補一覧を見て引数を合わせる
TS2741 Property 'x' is missing in type 'A' but required in type 'B' 必須プロパティが1つ不足 オブジェクトの書き忘れ 追加するか ? にする
TS2739 Type 'A' is missing the following properties from type 'B': x, y 必須プロパティが複数不足 同上(2〜4件) 不足分を追加
TS2353 Object literal may only specify known properties… 型にないプロパティを書いた 余計なキー、つづり違い キーを消すか型に追加
TS2375 …with 'exactOptionalPropertyTypes: true' 省略可能プロパティに undefined を明示代入 { title: undefined } キーごと省く、型に | undefined
TS2352 Conversion of type 'X' to type 'Y' may be a mistake… 無理な型アサーション "abc" as number 値を変換する
TS2416 Property 'x' in type 'A' is not assignable to the same property in base type 'B' 継承でメソッドの型が合わない 親と戻り値が違う 親の型に合わせる
TS4114 This member must have an 'override' modifier… override が必要 noImplicitOverride 有効時 override を付ける
TS2564 Property 'x' has no initializer… クラスのプロパティ未初期化 constructor で代入していない 初期値、constructor で代入
TS2355 A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value 戻り値を返していない return の書き忘れ return を書く
TS7030 Not all code paths return a value 一部の分岐で return がない noImplicitReturns 有効時 全分岐で return
TS1308 'await' expressions are only allowed within async functions… async でない関数で await async の付け忘れ async function にする
TS2365 Operator '+' cannot be applied to types 'X' and 'Y' その型同士で演算できない number と bigint、配列の足し算 型をそろえる
TS2367 This comparison appears to be unintentional… 比較が常に false union にない値と比較 union に追加、値を直す
TS2349 This expression is not callable 関数でないものを呼んだ プロパティ名の取り違え 呼び出しをやめる、型を確認
TS2693 'X' only refers to a type, but is being used as a value here 型を値として使った type を変数のように使う 値(定数・クラス)を用意する
TS2540 Cannot assign to 'x' because it is a read-only property readonly に代入 readonly、as const 新しいオブジェクトを作る
TS2588 Cannot assign to 'x' because it is a constant const に再代入 const 変数の更新 let にするか別変数
TS2451 Cannot redeclare block-scoped variable 'x' 同じ名前を二重宣言 let の重複、モジュールでないファイル 名前を変える、export {}
TS2448 Block-scoped variable 'x' used before its declaration 宣言より前で使用 定数を下で宣言 宣言を上へ移す
TS4111 Property 'x' comes from an index signature… インデックス型はブラケットで参照 noPropertyAccessFromIndexSignature env["API_URL"]
TS2589 Type instantiation is excessively deep and possibly infinite 型の再帰が深すぎる 再帰型・巨大な条件型 再帰を浅くする、型を分割
TS1005 'x' expected 構文の記号が足りない 括弧・カンマの閉じ忘れ 指摘位置の直前を確認
TS1128 Declaration or statement expected 余計な記号がある } が多い 括弧の対応を確認
TS6133 'x' is declared but its value is never read 未使用の変数 noUnusedLocals 有効時 削除、または _ で始める(引数)

本記事の内容は、ご自由にお使いください。
ご利用の際は、出典として本ページへのリンクを記載いただけますようお願いします。

(記載例)出典:株式会社RJC「TypeScriptエラー一覧|TS2322・TS2345等の意味と直し方50選」

エラーメッセージの読み方と直し方の判断基準

長いエラーは「最後の行」から読む

TypeScript のエラーは、上の行ほど大きな単位、下の行ほど具体的な原因です。 次は TS2375 の実際の出力(7.0.2、--pretty true の既定表示)です。

main.ts:4:7 - error TS2375: Type '{ title: string | undefined; }' is not assignable to type 'Options' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Types of property 'title' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.

4 const opts: Options = { title };
        ~~~~

Found 1 error in main.ts:4
読む順 行 わかること
1 一番下 Type 'undefined' is not assignable to type 'string' 本当の原因は「undefined が入りうること」
2 その上 Types of property 'title' are incompatible 問題のプロパティは title
3 1行目 どの代入(opts)で起きたか
4 ~~~~ の位置 エディタで飛ぶ場所

読む順のコツは「最下行で原因、1行目で場所」です。 1行目だけを読むと「型が合わない」としかわからず、as で黙らせたくなりますが、最下行を見れば「undefined の扱い」が論点だとわかります。

「any で黙らせない」ための判断表

状況 選ぶ直し方 理由
値の形が実際に違う(string を number に) 値を変換する(Number(v)) 実行時の不具合をそのまま直せる
null / undefined の可能性 早期 return・?.・?? 型と実行時の両方で安全
外部から来るデータ(JSON・API) unknown で受けて型ガード 形を確認してから使える
型定義が実態より狭い 型定義を直す 次に使う人も助かる
ライブラリの型が足りない @types 導入か .d.ts 追加 any が広がらない
どうしても今は直せない // @ts-expect-error 理由 直ったときに TS2578 で知らせてくれる

as や any は「チェックを止める」操作で、原因はコードに残ります。 型ガードや unknown の詳しい使い分けは、それぞれ専用の記事(型ガード、any と unknown)で扱っているので、ここでは判断の入口だけに留めます。

strict系オプションとエラーの対応表

同じファイルをオプションだけ変えて tsc 7.0.2 で実行し、どのエラーが出るかを確かめました。

// strictdemo/main.ts
export {};
const scores: number[] = [80, 90];
const first = scores[0];
console.log(first.toFixed(1));
const stock: Record<string, number> = { pen: 3 };
console.log(stock["pen"].toFixed(0));
function f(x) { return x; }
const el = document.querySelector("#a");
el.id = "b";
type Opt = { memo?: string };
const o: Opt = { memo: undefined };
$ tsc --pretty false --noEmit --target es2022 --strict false main.ts
(出力なし)

$ tsc ... --strict false --noImplicitAny main.ts
main.ts(7,12): error TS7006: Parameter 'x' implicitly has an 'any' type.

$ tsc ... --strict false --strictNullChecks main.ts
main.ts(9,1): error TS18047: 'el' is possibly 'null'.

$ tsc ... --strict --noUncheckedIndexedAccess main.ts
main.ts(4,13): error TS18048: 'first' is possibly 'undefined'.
main.ts(6,13): error TS2532: Object is possibly 'undefined'.
main.ts(7,12): error TS7006: Parameter 'x' implicitly has an 'any' type.
main.ts(9,1): error TS18047: 'el' is possibly 'null'.

$ tsc ... --strict --exactOptionalPropertyTypes main.ts
main.ts(7,12): error TS7006: Parameter 'x' implicitly has an 'any' type.
main.ts(9,1): error TS18047: 'el' is possibly 'null'.
main.ts(11,7): error TS2375: Type '{ memo: undefined; }' is not assignable to type 'Opt' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Types of property 'memo' are incompatible.
    Type 'undefined' is not assignable to type 'string'.
オプション strict に含まれるか 増えるエラー 典型例
strictNullChecks 含まれる TS18047・TS18048・TS2531・TS2532・TS2454 querySelector の結果を直接使う
noImplicitAny 含まれる TS7006・TS7031・TS7053・TS7016 引数に型がない
noImplicitThis 含まれる TS2683 通常関数内の this
strictPropertyInitialization 含まれる TS2564 クラスのプロパティ未初期化
useUnknownInCatchVariables 含まれる TS18046 catch (e) の e を直接使う
noUncheckedIndexedAccess 含まれない TS18048・TS2532 arr[0]・record[key] が T | undefined に
exactOptionalPropertyTypes 含まれない TS2375・TS2412 { memo: undefined }
noPropertyAccessFromIndexSignature 含まれない TS4111 env.API_URL
noImplicitOverride 含まれない TS4114 override の付け忘れ
noImplicitReturns 含まれない TS7030 一部分岐で return なし
noUnusedLocals / noUnusedParameters 含まれない TS6133 未使用の変数・引数

TypeScript 7.0 では strict の既定値が true になりました。 上と同じファイルをオプションなしで実行すると、7.0.2 は TS7006 と TS18047 を出し、5.9.3 は何も出しませんでした。また 7.0.2 の tsc --init が作る tsconfig.json には noUncheckedIndexedAccess: true と exactOptionalPropertyTypes: true が最初から入っています。新しく作ったプロジェクトで TS18048・TS2532・TS2375 が急に増えたら、この2つのオプションが理由です。 各オプションの推奨値は tsconfig の記事で扱っています。

50件の再現コードとtsc 7.0.2の出力

以下はすべて、ファイルを1つずつ tsc --strict --pretty false --target es2022 --lib es2022,dom --noEmit --module esnext --moduleResolution bundler main.ts で実行した出力です(各ファイルの先頭の export {}; は、ファイルをモジュール扱いにして名前の衝突を防ぐためのものです)。5.9.3 でも出力は同じで、違いがあったものだけ注記しています。 コードは読みやすさのため1ブロックにまとめていますが、実行はケースごとに別ファイルです。出力の行・列番号は、先頭に export {}; を置いた各ファイルでの位置です。

型が合わないとき(TS2322・TS2345・TS2741ほか12件)

// TS2322
let count: number = "10";
// TS2345
function double(n: number) { return n * 2; }
double("3");
// TS2741
type Task = { id: number; title: string };
const t: Task = { id: 1 };
// TS2739
type Item = { id: number; name: string; price: number };
const item: Item = { id: 1 };
// TS2353
const t: Task = { id: 1, title: "A", done: false };
// TS2375(--exactOptionalPropertyTypes)
type Options = { title?: string };
const title: string | undefined = undefined as string | undefined;
const opts: Options = { title };
// TS2352
const n = "abc" as number;
// TS2416
class Animal { speak(): string { return "..."; } }
class Dog extends Animal { speak(): number { return 1; } }
// TS2769
function toLabel(id: number): string;
function toLabel(name: string): string;
function toLabel(v: number | string): string { return String(v); }
toLabel(true);
// TS2554
function greet(name: string) { return `Hi ${name}`; }
greet("Sato", "Suzuki");
// TS2556
function sum(a: number, b: number) { return a + b; }
const nums = [1, 2];
sum(...nums);
// TS2794
const p = new Promise((resolve) => { resolve(); });
main.ts(2,5): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(3,8): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
main.ts(3,7): error TS2741: Property 'title' is missing in type '{ id: number; }' but required in type 'Task'.
main.ts(3,7): error TS2739: Type '{ id: number; }' is missing the following properties from type 'Item': name, price
main.ts(3,38): error TS2353: Object literal may only specify known properties, and 'done' does not exist in type 'Task'.
main.ts(4,7): error TS2375: Type '{ title: string | undefined; }' is not assignable to type 'Options' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Types of property 'title' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.
main.ts(2,11): error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
main.ts(3,28): error TS2416: Property 'speak' in type 'Dog' is not assignable to the same property in base type 'Animal'.
  Type '() => number' is not assignable to type '() => string'.
    Type 'number' is not assignable to type 'string'.
main.ts(7,9): error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'string'.
main.ts(3,15): error TS2554: Expected 1 arguments, but got 2.
main.ts(4,5): error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter.
main.ts(2,38): error TS2794: Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'?

5.9.3 との違い(TS2769): 5.9.3 はオーバーロードの候補をすべて列挙します。7.0.2 は最後の候補の理由だけを表示します。

(5.9.3)
main.ts(7,9): error TS2769: No overload matches this call.
  Overload 1 of 2, '(id: number): string', gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'number'.
  Overload 2 of 2, '(name: string): string', gave the following error.
    Argument of type 'boolean' is not assignable to parameter of type 'string'.

直す前と後(よく出る3件)

// TS2345:フォームの値は string。呼び出し側で変換する
const raw = "3";
double(Number(raw));

// TS2556:長さを固定するなら as const でタプルにする
const pair = [1, 2] as const;
sum(...pair);

// TS2794:値を返さない Promise は void を指定する
const done = new Promise<void>((resolve) => { resolve(); });

null・undefinedの可能性があるとき(TS18047・TS2532ほか6件)

// TS2531
function findTitle(): string | null { return null; }
findTitle().length;
// TS18047
const el = document.querySelector("#title");
el.textContent = "Hello";
// TS18048
function greet(name?: string) { return name.toUpperCase(); }
// TS2532
const items = [{ id: 1, name: "pen" }];
console.log(items.find((i) => i.id === 2).name);
// TS18046
const data: unknown = JSON.parse("{}");
data.id;
// TS2454
let message: string;
console.log(message);
main.ts(3,1): error TS2531: Object is possibly 'null'.
main.ts(3,1): error TS18047: 'el' is possibly 'null'.
main.ts(3,10): error TS18048: 'name' is possibly 'undefined'.
main.ts(3,13): error TS2532: Object is possibly 'undefined'.
main.ts(3,1): error TS18046: 'data' is of type 'unknown'.
main.ts(3,13): error TS2454: Variable 'message' is used before being assigned.

TS2531・TS2532 は「式」、TS18047・TS18048 は「変数名」に対して出ます。 変数に受けると、エラー文に変数名が入ってわかりやすくなります。

// 直した後
const el2 = document.querySelector("#title");
if (el2) el2.textContent = "Hello";             // 絞り込み

function greet2(name?: string) {
  return (name ?? "guest").toUpperCase();         // 既定値
}

const found = items.find((i) => i.id === 2);
console.log(found?.name ?? "not found");          // ?. と ??

名前・プロパティが見つからないとき(TS2339・TS2304ほか12件)

// TS2339
const user = { name: "Sato" };
console.log(user.age);
// TS2551
const tags = ["a", "b"];
console.log(tags.lenght);
// TS2304
const total = calcTotal([1, 2, 3]);
// TS2552
const userName = "Sato";
console.log(usrName);
// TS2693
type Item = { id: number };
const x = Item;
// TS2349
const config = { port: 8080 };
config.port();
// TS4111(--noPropertyAccessFromIndexSignature)
type Env = { [key: string]: string };
declare const env: Env;
console.log(env.API_URL);
// TS7053
const prices = { pen: 100, note: 200 };
function priceOf(key: string) { return prices[key]; }
// TS2540
type Item = { readonly id: number };
const item: Item = { id: 1 };
item.id = 2;
// TS2588
const limit = 10;
limit = 20;
// TS2451
let id = 1;
let id = 2;
// TS2448
console.log(total);
const total = 100;
main.ts(3,18): error TS2339: Property 'age' does not exist on type '{ name: string; }'.
main.ts(3,18): error TS2551: Property 'lenght' does not exist on type 'string[]'. Did you mean 'length'?
main.ts(2,15): error TS2304: Cannot find name 'calcTotal'.
main.ts(3,13): error TS2552: Cannot find name 'usrName'. Did you mean 'userName'?
main.ts(3,11): error TS2693: 'Item' only refers to a type, but is being used as a value here.
main.ts(3,8): error TS2349: This expression is not callable.
  Type 'Number' has no call signatures.
main.ts(4,17): error TS4111: Property 'API_URL' comes from an index signature, so it must be accessed with ['API_URL'].
main.ts(4,10): error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ pen: number; note: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ pen: number; note: number; }'.
main.ts(4,6): error TS2540: Cannot assign to 'id' because it is a read-only property.
main.ts(3,1): error TS2588: Cannot assign to 'limit' because it is a constant.
main.ts(2,5): error TS2451: Cannot redeclare block-scoped variable 'id'.
main.ts(3,5): error TS2451: Cannot redeclare block-scoped variable 'id'.
main.ts(2,13): error TS2448: Block-scoped variable 'total' used before its declaration.
main.ts(2,13): error TS2454: Variable 'total' is used before being assigned.

TS2448 は TS2454 とセットで出ます。 宣言を上に移せば両方消えます。TS7053 は key の型を広い string から、使えるキーだけに狭めると直ります。

// TS7053 を直した後
function priceOf2(key: keyof typeof prices) {
  return prices[key];                // number
}
priceOf2("pen");

TS2451 は、import・export がないファイル同士で同じ名前を宣言しても出ます(グローバルスコープを共有するため)。ファイルに export {}; を書くか、moduleDetection: "force" でモジュール扱いにすると解消します。

型が推論できずanyになるとき(TS7006・TS7031・TS2683)

// TS7006
function add(a, b) { return a + b; }
// TS7031
function show({ id, title }) { return `${id}:${title}`; }
// TS2683
function getName() { return this.name; }
main.ts(2,14): error TS7006: Parameter 'a' implicitly has an 'any' type.
main.ts(2,17): error TS7006: Parameter 'b' implicitly has an 'any' type.
main.ts(2,17): error TS7031: Binding element 'id' implicitly has an 'any' type.
main.ts(2,21): error TS7031: Binding element 'title' implicitly has an 'any' type.
main.ts(3,10): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
// 直した後
function add2(a: number, b: number) { return a + b; }
function show2({ id, title }: { id: number; title: string }) { return `${id}:${title}`; }
function getName2(this: { name: string }) { return this.name; }   // this は型注釈専用の引数

関数・クラス・演算のエラー(TS2355・TS2564ほか8件)

// TS2355
function getCount(): number { console.log("count"); }
// TS7030(--noImplicitReturns)
export function label(n: number) { if (n > 0) { return "plus"; } }
// TS2564
class Item { name: string; }
// TS4114(--noImplicitOverride)
class Base { run() {} }
class Child extends Base { run() {} }
// TS1308
function load() { await fetch("/api/items"); }
// TS2365
const a = [1] + 1n;
const ok = {} < 1;
// TS2367
type Status = "open" | "closed";
function check(s: Status) { if (s === "done") {} }
// TS2589
type Repeat<T, N extends number, A extends T[] = []> =
  A["length"] extends N ? A : Repeat<T, N, [...A, T]>;
type Big = Repeat<string, 5000>;
main.ts(2,22): error TS2355: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.
main.ts(2,17): error TS7030: Not all code paths return a value.
main.ts(3,3): error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.
main.ts(3,28): error TS4114: This member must have an 'override' modifier because it overrides a member in the base class 'Base'.
main.ts(3,3): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.
main.ts(2,11): error TS2365: Operator '+' cannot be applied to types 'number[]' and 'bigint'.
main.ts(3,12): error TS2365: Operator '<' cannot be applied to types '{}' and 'number'.
main.ts(4,7): error TS2367: This comparison appears to be unintentional because the types 'Status' and '"done"' have no overlap.
main.ts(4,12): error TS2589: Type instantiation is excessively deep and possibly infinite.

TS2564 の直し方は3通りあり、値が決まるタイミングで選びます。

値が決まるタイミング 書き方
作成時に決まる name = "";(初期値)
constructor の引数で決まる constructor(public name: string) {}
外部の仕組み(DI など)が後から入れる name!: string;(確実に入る場合だけ)

import・モジュールのエラー(TS2307・TS7016ほか6件)

// TS2307
import { format } from "./utils/format";
// TS2305(lib.ts は formatTime だけを export)
import { parseCsv } from "./lib";
// TS2614(button.ts は export default function Button)
import { Button } from "./button";
// TS2835(--module nodenext、package.json に "type": "module")
import { format as f2 } from "./format";
// TS7016(node_modules/untyped-lib は index.js だけ)
import { hello } from "untyped-lib";
// TS2742 / TS2883(--declaration、依存の依存にある型を返す)
import { createStore } from "store-lib";
export const store = createStore();
main.ts(1,24): error TS2307: Cannot find module './utils/format' or its corresponding type declarations.
main.ts(1,10): error TS2305: Module '"./lib"' has no exported member 'parseCsv'.
main.ts(1,10): error TS2614: Module '"./button"' has no exported member 'Button'. Did you mean to use 'import Button from "./button"' instead?
main.ts(1,24): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './format.js'?
main.ts(1,23): error TS7016: Could not find a declaration file for module 'untyped-lib'. '/…/cases/7016/node_modules/untyped-lib/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/untyped-lib` if it exists or add a new declaration (.d.ts) file containing `declare module 'untyped-lib';`
main.ts(2,14): error TS2883: The inferred type of 'store' cannot be named without a reference to 'Store' from 'store-lib/node_modules/store-core'. This is likely not portable. A type annotation is necessary.

(TS7016 の絶対パスは途中を省略しています。)

5.9.3 との違い(TS2742 → TS2883): 同じコードで 5.9.3 は TS2742 を出しました。7.0.2 では番号が TS2883 になり、メッセージに型名('Store')が入ります。

(5.9.3)
main.ts(2,14): error TS2742: The inferred type of 'store' cannot be named without a reference to 'store-lib/node_modules/store-core'. This is likely not portable. A type annotation is necessary.

TS2742/TS2883 は、declaration: true(ライブラリやモノレポで .d.ts を出す設定)のときに、推論された型が「自分の依存の、さらに依存」にあると出ます。直し方は、公開する変数・関数に戻り値の型を明示することです。型が依存の奥にあるなら、その型を export しているパッケージを直接の依存に加えて import します。

TS2614 で名前付き import を default import に変えるとき、default export が見つからない逆のケースは TS1192(Module has no default export)になります。

構文・未使用のエラー(TS1005・TS1128・TS6133)

// TS1005
const list = [1, 2, 3;
// TS1128
function f() {
  return 1;
}
}
// TS6133(--noUnusedLocals)
export function g() {
  const unused = 1;
  return 2;
}
main.ts(2,23): error TS1005: ',' expected.
main.ts(5,1): error TS1128: Declaration or statement expected.
main.ts(3,9): error TS6133: 'unused' is declared but its value is never read.

構文エラー(TS1000番台)は、指摘位置の「1つ前」に原因があることが多いです。 TS1005 は ] の閉じ忘れなのに「, が必要」と出ています。括弧の対応はエディタの括弧ハイライトで確認すると早いです。

エラー番号の範囲で分類を見分ける

範囲 種類 例
1000番台 構文(パース)エラー TS1005、TS1128、TS1308
2000番台 型チェックの意味エラー TS2322、TS2339、TS2769
4000番台 宣言・オプション由来のルール TS4111、TS4114
5000番台 コンパイラオプション・設定ファイル TS5112
6000番台 未使用などの情報系 TS6133
7000番台 暗黙の any など noImplicitAny 系 TS7006、TS7016、TS7053
18000番台 比較的新しく追加された診断 TS18046、TS18047、TS18048

TS5112 も 7.0 で出会いやすいエラーです。 tsconfig.json があるフォルダで tsc main.ts のようにファイルを指定すると、7.0.2 は次のエラーを出しました。

error TS5112: tsconfig.json is present but will not be loaded if files are specified on commandline. Use '--ignoreConfig' to skip this error.

ファイル単位で試すなら --ignoreConfig を付け、通常はファイルを指定せず tsc だけで実行します。

TypeScript 7.0と5.9の出力の違いまとめ

項目 5.9.3 7.0.2
50件のエラーコードと本文 同じ 同じ(下の2件を除く)
TS2769 の詳細 全オーバーロードの理由を列挙 最後の候補の理由だけ
依存の奥の型を推論 TS2742 TS2883(型名つき)
strict の既定値 false true
tsc --init の内容 — noUncheckedIndexedAccess・exactOptionalPropertyTypes が true
tsconfig があってファイル指定 そのまま実行 TS5112
1ファイルのチェック時間(この環境) 約5秒 約0.5秒

チェック時間は、この検証コンテナで TS7031 のファイルを time で計った値(5.9.3 が real 5.08s、7.0.2 が real 0.58s)です。7.0 は Go で書き直されたネイティブ版のため、起動を含めて速くなっています。

よくある質問

Q. TS2322 と TS2345 の違いは何ですか? A. どちらも「型が合わない」ですが、TS2322 は代入・戻り値・プロパティ、TS2345 は関数の引数で出ます。直し方は同じで、最下行の具体的な型の組み合わせを見て、値を変換するか型定義を直します。

Q. エラーを一時的に消したいときはどうすればよいですか? A. // @ts-ignore ではなく // @ts-expect-error 理由 を使うのがおすすめです。原因が直ってエラーがなくなると、今度は TS2578(Unused '@ts-expect-error' directive)が出るので、消し忘れを防げます。

Q. TS2531 と TS18047 は何が違いますか? A. 意味は同じ「null の可能性」です。findTitle().length のような式には TS2531、el.textContent のように変数には TS18047 が出ます。変数に受けて if で絞り込むと、どちらも直ります。

Q. TypeScript 7.0 にしたらエラーが増えました。 A. strict の既定値が true になったことが主な理由です。まず tsconfig.json に strict が明示されているかを確認してください。tsc --init で作った設定なら noUncheckedIndexedAccess と exactOptionalPropertyTypes も有効なので、TS18048・TS2532・TS2375 が増えます。

まとめ

  • エラー番号から逆引きすれば、原因と直し方のパターンはほぼ決まる(冒頭の50件の表)
  • 長いエラーは最下行で原因、1行目で場所を読む
  • any・as で黙らせる前に、変換・絞り込み・型定義の修正を検討する
  • null 系は TS2531/TS2532(式)と TS18047/TS18048(変数)、変数に受けて絞り込むと直る
  • strict 外のオプション(noUncheckedIndexedAccess など)で増えるエラーを対応表で把握する
  • 7.0.2 では TS2769 の表示、TS2742→TS2883、strict 既定 true が5.9からの主な違い

本記事の内容は、ご自由にお使いください。
ご利用の際は、出典として本ページへのリンクを記載いただけますようお願いします。

(記載例)出典:株式会社RJC「TypeScriptエラー一覧|TS2322・TS2345等の意味と直し方50選」

株式会社RJCでは、TypeScriptの型エラーの読み方と直し方を仲間と学び合っています。こうした知識を共有しながら、日々技術を磨いています。

株式会社RJC ― SI事業・SES事業・AI駆動開発。RJCは一緒に成長を楽しめる会社です。

WE ARE HIRING

RJCで一緒に開発しながら、
成長を楽しみませんか?

RJCは、Web・モバイル・AIを活用した開発プロジェクトで、テックリードやPM・PMOも活躍するシステム開発会社です。会社を知る、待遇を確かめる、話を聞いてみる。気になるところ見てみてください!

  • 127日年間休日
  • 12時間平均残業時間
  • 毎日ガチャ遊びココロも大切にする福利厚生。アマギフなどの賞品ラインナップ!

ほかにも、チケットレストラン、書籍読み放題、2年ごとの慰労報奨(休暇 or 金一封)、11期連続の黒字決算。

ABOUT RJC RJCがどんな会社か知る 考え方、研修、働き方、福利厚生、社員の前職まで。RJCのことが丸わかり! RJC丸わかりページへ JOB DESCRIPTION 仕事内容・待遇を見てみる 仕事内容、給与・待遇、選考の流れ。経験者も未経験も!応募前に知りたいこと、まとめました! 募集要項を見る ENTRY エントリーする エントリーは1〜2分・履歴書不要です。まずは話を聞いてみたい、という方でも歓迎です! エントリーフォームへ

RJCで一緒に開発しながら、 成長を楽しみませんか?