Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Toy example of a messages interface for typescript
interface IMessage<TKey extends string, TPayload> {
key: TKey;
payload: TPayload;
}
type GenericMessage = IMessage<string, any>;
module foo {
type FooBarKeyT = "foo.bar";
const FooBarKey: FooBarKeyT = "foo.bar";
type FooQuuxKeyT = "foo.quux";
const FooQuuxKey: FooQuuxKeyT = "foo.quux";
export type FooBar = IMessage<FooBarKeyT, {v: number}>;
export type FooQuux = IMessage<FooQuuxKeyT, {v: string}>;
export type FooMessage = FooBar | FooQuux;
export function isFooMessage(m:GenericMessage): m is FooMessage {
return m.key === FooBarKey || m.key === FooQuuxKey;
}
export function isFooBarMessage(m:FooMessage): m is FooBar {
return m.key === FooBarKey;
}
export function isFooQuuxMessage(m:FooMessage): m is FooQuux {
return m.key === FooQuuxKey;
}
export function fooBarMessage(v: number): FooMessage {
return {key: FooBarKey, payload: {v: v}};
}
export function fooQuuxMessage(v: string): FooMessage {
return {key: FooQuuxKey, payload: {v: v}};
}
}
module consumer {
const m:GenericMessage = foo.fooBarMessage(23);
if (foo.isFooMessage(m)) {
if (foo.isFooBarMessage(m)) {
console.log(Math.pow(2, m.payload.v));
}
else if (foo.isFooQuuxMessage(m)) {
console.log(m.payload.v.toUpperCase());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment