0

I am trying to find proper signature (current version of TypeScript is 1.7) for function that should accept only reference types, not primitives:

function onlyObject(x: ???) {
    if (typeof x !== 'object') {
        throw "bad arg!";
    }
}

So for function above this should work:

onlyObject({ });
onlyObject(new Date());
onlyObject(new Number(1));
onlyObject(null);
onlyObject(function () { });

but this will fail in compile time:

onlyObject("awd");
onlyObject(1);
onlyObject(false);
4
  • there is a type called Object, but last I heard there was a bug in typescript that allowed anything to be sent when used. Commented Jan 15, 2016 at 20:36
  • function onlyObject(x: Date | Number | void | Function){} ????? I don't believe TypeScript differentiates between a number and a Number or a string and a String, so you might have to exclude those. Or maybe rethink how you are approaching the problem. Ideally you only have a single type for a single variable. Commented Jan 15, 2016 at 20:36
  • Also, onlyObject(1) and onlyObject(new Number(1)) are pretty much the same in JavaScript since they both act as objects when they are treated as one, once they are assigned to a variable. Commented Jan 15, 2016 at 20:40
  • @Jon49 Well, I'd like to have a function for which typeof x === 'object' is true. Regarding differentiation between string and String - TypeScript does a bit, you can check it here: bit.ly/1ZBweTs Commented Jan 15, 2016 at 20:42

1 Answer 1

3

There currently isn't a way to express this in the language.

If you're feeling industrious, you can add it, as the project is accepting pull requests for this feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.