How I can describe follow JS code

Topics: General
Oct 2, 2012 at 12:08 PM
Edited Oct 2, 2012 at 12:11 PM

In JS we offen pass args of different types to functons. in TypeScript we describe this using overload.

function f(n: number);
function f(s: string);
// but in other case
// is object OR string
// options.selector is string OR function
function f(options) { }
I don't see how to describe "options" arg using TypeScript type system. May be need expand language? I think it's very common use case
Oct 2, 2012 at 6:42 PM

You can use an interface but I do not know a way for allowing multiple types:

interface fOptionsData {
	str: string;

interface fOptions {
	data: fOptionsData;

function test(options : fOptions) {

test({data: {str : "Hello World!"}});
Oct 2, 2012 at 8:08 PM
Edited Oct 2, 2012 at 8:08 PM

You can use method overloading but the final definition needs to be of type any. Example:

class Foo {
     public bar(n: number);
     public bar(s: string);
     public bar(o: any): void {
          if (o typeof "string") {
          } else if (o typeof "number") {