Last active
May 20, 2016 06:08
-
-
Save brehaut/2321016e2e5e42c96f834cb8716b2710 to your computer and use it in GitHub Desktop.
Toy example of a messages interface for typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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