TypeScript:クラスとそのメソッドを別々のファイルに定義する

StackOverflow https://stackoverflow.com//questions/12706290

  •  13-12-2019
  •  | 
  •  

質問

クラスを1つのファイルに宣言し、そのメソッドを別々のファイルに定義することは可能ですか?

私はのメソッドののあるクラスを持っています、そして私がそれらを少し広げることができればそれは素晴らしいでしょう。

役に立ちましたか?

解決

短回答: TypeScriptは、クラス定義を複数のファイルに分割することをサポートしません。

回避策:クラスのメンバーを含むインターフェイスとそのインタフェースを実装する2つの異なるクラスを定義できます。次に、1つのクラスからもう一方のクラスへのミックスインプロパティを作成してクラスを組み合わせたものにします。例えば:

largeclass.a.ts

interface LargeClass {
   methodA(): string;
   methodB(): string;
}

class LargeA implements LargeClass {
   methodA: () => string; // not implemented, needed since otherwise we don't extend LargeClass
   methodB() {
     return "Hello world";
   }
}
.

largeclass.b.ts

class LargeB implements LargeClass {
   methodA() {
     return "Foo";
   }
   methodB: () => string; // not implemented, needed since otherwise we don't extend LargeClass
}
.

USAGE.TS

// Using underscore's extend to copy implementation from A to B
var c:LargeClass = _.extend(new LargeA(), new LargeB());

// Manually mixing in a to b
var a = new LargeA();
var b:LargeClass = new LargeB();
for (var prop in a) {
    b[prop]=a[prop];
}
.

クラスのコンストラクターが必要な場合は機能しません。そして本当にそれは最適です...回避策なし:)

OHは、TypeScriptがクラスのUnitialisedプロパティ/フィールドタイプの宣言を受信しないため、これは機能します - タイプチェックにのみ使用します。

私はまた、あなたがインターフェースなしでこれを行うことができることを理解しています。

他のヒント

クラス自体

以外のファイルからの機能をインポートできます。

クラスファイルの例:

import {func1, func2, func3} from "./functions"

class MyClass {
   public foo: string = "bar"
   public func1 = func1.bind(this)
   public func2 = func2.bind(this)
   public func3 = func3.bind(this)
}
.

これは1つの関数ファイルの例です。

import {MyClass} from "./MyClass"

export function func1(this: MyClass, param1: any, param2: any){
   console.log(this.foo)
   ...
} 
.

重要な注意:矢印関数のバインド(この)ができないため、エクスポートされた各関数が矢印関数ではないことを確認してください

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top