class
私が書いている多くのメソッドは、暗黙のうちに同じ関数型を持っています。私がやりたいのは、この関数型を強制して、特定のメソッドが関数型に準拠する必要があることを明示的に述べることができるようにすることです。
例えば
interface MyFunctionType {(resource: string | Resource): Something}
私のクラスには、このインターフェースに準拠するいくつかのメソッドがあります。
class MyClass {
// ...
someMethod() { /*...*/ }
someMethodThatConforms(resource: string | Resource) {
// ...
return new Something(/*...*/);
}
anotherMethodThatConforms(resource: string | Resource) {
// ...
return new Something(/*...*/);
}
someOtherMethod() { /*...*/ }
// ...
}
私がいることを知っているsomeMethodThatConforms
とanotherMethodThatConforms
インターフェースに準拠しますが、今、私はない方法を知りたい主張していることsomeMethodThatConforms
とanotherMethodThatConforms
のインタフェースを準拠しなければなりませんMyFunctionType
(Iチェンジた場合、そのことをMyFunctionType
、エラーがスローされますか)?
別のインターフェースを定義してMyClass
実装することができます。
interface MyFunctionType {(resource: string | Resource): Something}
interface FixedMethods {
someMethodThatConforms: MyFunctionType;
// you can add more
}
class MyClass implements FixedMethods {
someMethodThatConforms(resource: string | Resource) {
// this method will fail type check, until we return a Something
return 1;
}
}
より複雑な方法:mapped type
ジェネリック型を作成するために使用します。
interface MyFunctionType { (resource: string | Resource): Something }
// a Mapped Type to fix methods, used in place of a interface
type FixedMethods<T extends string> = {
[k in T]: MyFunctionType
}
class MyClass implements FixedMethods<"someMethodThatConforms" | "anotherMethodThatConforms"> {
someMethodThatConforms(resource: string | Resource) {
// this method will fail type check, until we return a Something
return 1;
}
// it also complains about lack of "anotherMethodThatConforms" method
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加