Steve
Steve

Reputation: 333

Typescript: is there a way to restrict something to just a javascript 'object' type?

I thought using the type Object would do it, but that still allows anything. I want something like this:

function foo(arg: /* what goes here? */) { }

foo({})                        // should compile
foo({ something: 'anything'})  // should compile
foo(new Object())              // should compile

foo(7)                         // should not compile
foo('hello')                   // should not compile

Upvotes: 0

Views: 165

Answers (1)

Max Brodin
Max Brodin

Reputation: 3938

There is no way to set Javascript Object type constraint in the compile time in TypeScript 1.4. But you can still check the type in the run-time.

function foo(arg: Object) {
    if (typeof arg !== "object") { throw new Error("Error"); }

    console.log(arg);
}

Upvotes: 2

Related Questions