0

This pretty much standard way of defining a javascript object (or namespace of functions) fails in typescript, saying that publicFunction does not exist on type {}. Is this by design?

var MyObject = function (){
  var that = {};

  var privateFunction = function () {};
  that.publicFunction = function () {};

  return that;
}();

PS: Found a "fix" to it by changing the first line to var that = <any>{}; but I was wondering why is this necessary.

2
  • TypeScript has internal and external modules, you don't necessarily need to use this "standard way". Commented Feb 14, 2015 at 16:31
  • Yes, I'm aware of those but I already have tons of valid javascript in my existing project. Commented Feb 14, 2015 at 23:32

2 Answers 2

2

TypeScript infers that to have type {}, an empty object. Probably it doesn't make much sense to have an object with any properties, though.

var that = {};

You've have worked around by assert it to have type any. Another way to do it is:

var that;
that = {};

This way TypeScript doesn't infer variable type.

To take profit of TS advantages, you're better at declaring all object members at once. If you can't, you could use an interface:

interface MyObjectInterface {
    publicFunction();
}

var MyObject = function (){
  var that = <MyObjectInterface>{};

  var privateFunction = function () {};
  that.publicFunction = function () {};

  return that;
}();
Sign up to request clarification or add additional context in comments.

Comments

1

Knowing nothing about typescript, I'm going to hazard a guess that, judging by its name, it is strictly-typed. This means you can't define properties on objects that weren't there when the object was created.

<any>{} overrides this restriction, giving you an object that you can define arbitrary properties on.

The "correct" way would probably be:

var that = {
    publicFunction: function () {}
};

1 Comment

Your guesses are all correct. One more thing to mention is that returning an <any>{} will make it impossible for the compiler to check further usages of that returned object...

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.