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"; にします。

この問題を解いてみる →

パターン4

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

RunnerはrunメソッドをAthleteに要求します。実装しないままimplementsするとエラーになります。

直し方: (空) を run(): string { return "go"; } にします。

この問題を解いてみる →

パターン5

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

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

直し方: (空) を label = "box"; にします。

この問題を解いてみる →

よくある誤解

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

実務での勘所

interfaceはTypeScript独自の概念で、コンパイル後のJavaScriptには一切の痕跡を残しません。tscは型チェックが終わった時点でinterfaceの定義そのものを完全に削除します。そのため、実行時にif (x instanceof SomeInterface)のような判定をすることはできません。実行時にも型の情報を残したい場合はclassを使う必要があり、これがinterfaceとabstract classの実務上の使い分けの大きな判断基準の1つになっています。

演習をはじめる

関連するエラー

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