Skip to content

Instantly share code, notes, and snippets.

@jwmcpeak
Created December 8, 2012 01:32
Show Gist options
  • Save jwmcpeak/4238067 to your computer and use it in GitHub Desktop.
Save jwmcpeak/4238067 to your computer and use it in GitHub Desktop.
TypeScript Overload with No Parameters
// constructor
class Foo {
constructor ();
constructor (parm: string);
constructor (obj?: any) {
// implementation
}
}
// function
function foo(): void;
function foo(x: string): void;
function foo(y: number): void;
function foo(z?: any) {
if (typeof z === "string") {
} else if (typeof z === "number") {
} else {
}
}
// method
class Foo {
foo(): void;
foo(name: string): void;
foo(obj?: any) {
// implementation
}
}
@jwmcpeak
Copy link
Author

jwmcpeak commented Dec 9, 2012

This optional parameter approach is much better. Setting a default value of undefined resulted in the following JavaScript:

if (typeof obj === "undefined") { obj = undefined; }

As an aside, I thought I tried optional parameters in my initial testing. Apparently I did it wrong...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment