イベントを公開して購読することができるTypescriptでシンプルなイベントバスクラスを開発しようとしています。 パブリッシュされたトピックと公開されたデータのインターフェイスとの間のバインディングを持つことは良いことです。関数とクラスジェネリックを使ってこれを達成しようとしましたが、私のテストケースのいくつかが期待通りに動作していませんでした(失敗すると予想される行はOKです)。私はまた、期待通りに動作するhttps://www.typescriptlang.org/docs/handbook/generics.html からの例を追加しました。実際の状況では、トピックのインスタンスをどこかにシングルトンとして保存する予定です。Typescriptジェネリック関数が期待どおりに動作しない - 必要以上に別のジェネリック型を含むパラメータがコンパイルされるOK
interface BaseMessage { };
interface MyMessage extends BaseMessage {
a: number;
};
interface MyMessage2 extends BaseMessage {
b: string;
}
class Topic<A> {}
class MyTopic extends Topic<MyMessage> { };
class MyTopic2 extends Topic<MyMessage2> { };
class MyTopic3 extends Topic<MyMessage2> { }; // example of another topic using the same message interface
class EventBus {
publish<T extends BaseMessage> (topic: Topic<T>, data: T): void {}
subscribe<T extends BaseMessage>(topic: Topic<T>, callback: (arg?: T) => void): void { }
loggingIdentity<T>(arg: Array<T>): Array<T> {
return arg;
}
loggingIdentity2<T>(arg: Topic<T>): Topic<T> {
return arg;
}
}
class Test {
init(): void {
let eb = new EventBus();
eb.loggingIdentity<MyMessage2>(new Array<MyMessage2>()); // works just fine
eb.loggingIdentity<MyMessage2>(new Array<MyMessage>()); // error as expected
eb.loggingIdentity2<MyMessage2>(new Topic<MyMessage2>()); // works just fine
eb.loggingIdentity2<MyMessage2>(new Topic<MyMessage>()); // I am expecting this to fail, but this works
eb.publish<MyMessage2>(new MyTopic2(), { a: 1 }); // fails on not satisfying data parameter interface - expected
eb.publish<MyMessage2>(new MyTopic2(), { b: "hello" }); // works just fine
eb.publish<MyMessage2>(new MyTopic(), { b: "hello" }); // I am expecting this to fail, because of the first parameter, but it works
}
}
多分私はそこに何かを欠いています。どんな助けでも感謝します、ありがとう。ここで
おかげで、それは動作しますが、クラスのトピックをこのように更新するのに十分である:クラスのトピック {プライベートメンバを拡張します} –