Skip to content

Instantly share code, notes, and snippets.

@danatcofo
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danatcofo/9116918 to your computer and use it in GitHub Desktop.
Save danatcofo/9116918 to your computer and use it in GitHub Desktop.
turn your typescript modules into functions
/*
* This is an example of how to turn your typescript modules into functions.
*/
function Example(command: string, ...params: any[]): void;
function Example(command: string, ...params: any[]): any {
var isConstructor = false;
if (this instanceof Example && !this.__previouslyConstructedByExample) {
isConstructor = true;
this.__previouslyConstructedByExample = true;
}
switch (typeof (Example[command])) {
case "function":
if (isConstructor) {
return (function(cls, args){
function F(): void {
return cls.apply(this, args);
}
F.prototype = cls.prototype;
return new F();
})(Example[command], params);
}
return Example[command].apply(Example, params);
case "undefined": throw "unknown command call";
default:
if (isConstructor) throw "unknown command call";
return Example[command];
}
}
module Example {
export function Func0(parm1:string): string {
var ret = "Func0 was called: parm1 = " + parm1;
console.debug(ret);
return ret;
}
export function Func1(parm1:string, parm2: string): string {
var ret = "Func1 was called: parm1 = " + parm1 + ", parm2 = " + parm2;
console.debug(ret);
return ret;
}
export class Test {
public ret: string;
constructor(parm1: string, parm2: string){
this.ret = Func1(parm1, parm2);
}
}
}
var func0 = Example.Func0("hello world");
var func0_fn = <any>Example("Func0", "hello world");
console.assert(func0 == func0_fn, "single param example")
var func1 = Example.Func1("hello", "world");
var func1_fn = <any>Example("Func1", "hello", "world");
console.assert(func1 == func1_fn, "multi param example")
var test = new Example.Test("hello", "world");
var test_fn = new Example("Test", "hello", "world");
console.assert(test instanceof Example.Test, "class example");
console.assert(test_fn instanceof Example.Test, "function class example");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment