はじめに
TypeScriptを学び始めると必ずぶつかるのが型エラー。
そして大半の初心者が思うのが「エラーメッセージが全然優しくない…」です。
でも実は、よく出るエラーにはだいたい定番パターンがある。
この記事では、初心者がつまづきやすい型エラーを「症状」「原因」「解決策」で整理して、図鑑的にまとめます。
想定読者
- TypeScript初学者
- 案件でTypeScriptを使い始めた方
- 型エラーの読み方を身につけたい方
1. "Type 'undefined' is not assignable to type '〇〇'"
症状
let name: string = undefined;
Type 'undefined' is not assignable to type 'string'.
原因
-
string型にはundefinedが含まれていない - TypeScriptは「型安全」にうるさい
解決策
- 明示的に
undefinedを許容する
let name: string | undefined = undefined;
2. "Object is possibly 'null'"
症状
document.getElementById("app").innerHTML = "Hello";
Object is possibly 'null'.
原因
-
getElementById()の戻り値がHTMLElement | null - nullの可能性を無視すると怒られる
解決策
- nullチェックする
const el = document.getElementById("app");
if (el) {
el.innerHTML = "Hello";
}
- または非nullアサーションを使う(注意して使用)
document.getElementById("app")!.innerHTML = "Hello";
3. "Argument of type '〇〇' is not assignable to parameter of type '△△'"
症状
function greet(name: string) {}
greet(123);
Argument of type 'number' is not assignable to parameter of type 'string'.
原因
- 関数の引数に違う型を渡してる
解決策
- 呼び出し側の型を合わせる
greet("John");
4. "Property '〇〇' does not exist on type '△△'"
症状
const user = { id: 1, name: "John" };
console.log(user.email);
Property 'email' does not exist on type '{ id: number; name: string; }'.
原因
- 存在しないプロパティにアクセスしようとしてる
解決策
- プロパティを定義に追加する or アクセスをやめる
interface User {
id: number;
name: string;
email: string;
}
5. "Type 'any' is not assignable to type '〇〇'"
症状
let data: string = JSON.parse("{}");
Type 'any' is not assignable to type 'string'.
原因
-
JSON.parse()はanyを返す -
anyをそのまま型付けに使うと怒られる
解決策
- パース後に型アサーションする
interface User { id: number; name: string; }
const user = JSON.parse(json) as User;
- もしくは
zodなどで安全にパースする
6. "Cannot assign to '〇〇' because it is a constant"
症状
const count = 0;
count = 1;
Cannot assign to 'count' because it is a constant.
原因
-
constは再代入不可
解決策
- 変更したいなら
letを使う
let count = 0;
count = 1;
7. "Excess property checks"
症状
interface User { id: number; name: string; }
const user: User = { id: 1, name: "John", age: 20 };
Object literal may only specify known properties, and 'age' does not exist in type 'User'.
原因
- インターフェースにないプロパティを追加してる
解決策
- 定義に追加する or 削除する
interface User { id: number; name: string; age?: number; }
まとめ:型エラー攻略のコツ
- まずエラーメッセージを恐れず読む
- 「誰にどんな型を渡した?」を常に意識
- undefined / null / any あたりを丁寧に扱う
- 困ったら型定義に立ち戻る
TypeScriptの型エラーは最初は難しく感じますが、慣れるとむしろバグが減る最強の味方になります!
おわりに
Qiitaでは今後も初学者向けTipsを発信していきますので、ぜひLGTM・フォローお願いします!