classに定義したstaticメソッドをinterface
で型定義しようとして下記のように書いたらエラーになってしまったのでどうすればいいのか調べたのでMEMO📝
interface MyClassInterface { id: number, name: string, method(): void, static staticMethod(): void // 'static' 修飾子は型メンバーでは使用できません。ts(1070) } const MyClass: MyClassConstructor = class MyClass implements MyClassInterface { constructor(public id: number, public name: string){} method(){} static staticMethod(){} }
色々調べた結果、公式ドキュメントにまさにな内容が書いてあった🙌
simple way is to use class expressions https://www.typescriptlang.org/docs/handbook/interfaces.html#difference-between-the-static-and-instance-sides-of-classes
クラス式を使ってclassの返り値を変数代入時に型チェックすることでConstructorのインターフェースを満たしているか検証できるんですね✨
interface MyClassConstructor { new (id: number, name: string): MyClassInterface staticMethod(): void } interface MyClassInterface { id: number, name: string, method(): void } const MyClass: MyClassConstructor = class MyClass implements MyClassInterface { constructor(public id: number, public name: string){} method(){} static staticMethod(){} }
TypeScriptのissueでもこの辺のstaticのinterfaceの定義方法は議論されているみたいですね👀
あまり型を使う言語になれてないので色々勉強になる😓