Code Fix

中級

incorrectly implements interface の原因と直し方

クラスがimplementsで宣言したinterfaceのメンバー(メソッドやプロパティ)を実装し忘れたときに出るエラーです。interfaceは「このクラスが持つべき形」の契約であり、implementsはその契約を守る宣言です。

エラーメッセージの読み方

main.ts(4,7): error TS2420: Class 'Bot' incorrectly implements interface 'Greeter'.
main.ts
ファイル名
4
行番号
7
列番号 — この位置でtscが検査に失敗しました
TS2420
エラーコード — 検索するとTypeScriptの解説が見つかります
Class 'Bot' incorrectly implements interface 'Greeter'.
内容 — 期待していたもの、または受け付けられなかったもの

このエラーが出る典型パターン

パターン1

 1  interface Greeter {
 2    greet(): string;
 3  }
 4  class Bot implements Greeter {                                   
                                                   ^
 5  }
 6  console.log(new Bot());
main.ts(4,7): error TS2420: Class 'Bot' incorrectly implements interface 'Greeter'.

GreeterはgreetメソッドをBotに要求します。実装しないままimplementsすると、契約違反としてエラーになります。

直し方: (空) greet(): string { return "hi"; } にします。

この問題を解いてみる →

広告
広告スロット(未設定)

パターン2

 1  interface Sized {
 2    size(): number;
 3  }
 4  class Bag implements Sized {                               
                                               ^
 5  }
 6  console.log(new Bag());
main.ts(4,7): error TS2420: Class 'Bag' incorrectly implements interface 'Sized'.

Sizedはsizeメソッドを要求します。Bagクラスがそれを実装していないため契約違反になります。

直し方: (空) size(): number { return 0; } にします。

この問題を解いてみる →

パターン3

 1  interface Named {
 2    name: string;
 3  }
 4  class Robot implements Named {                 
                                          ^
 5  }
 6  console.log(new Robot());
main.ts(4,7): error TS2420: Class 'Robot' incorrectly implements interface 'Named'.

Namedはnameプロパティを要求します。Robotクラスにnameが無いため契約を満たせません。

直し方: (空) name = "R2D2"; にします。

この問題を解いてみる →

よくある誤解

「implementsと書けば自動的にメソッドの雛形が用意される」というわけではありません。implementsは契約を守っているかをtscに検査させるための宣言で、メソッドの中身は自分で書く必要があります。

まとめ

incorrectly implements interfaceは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

広告
広告スロット(未設定)