Default variables to the `any` type

Topics: Language Specification
Oct 3, 2012 at 3:56 PM
Edited Oct 3, 2012 at 3:58 PM

Is there any reason that TypeScript shouldn't default variables to the `any` type? Pun intended. ;)

For example, this code will generate warnings:

var obj = {};
obj.prop = "value";

To fix it we need to tell TypeScript that `obj` is of type `any`. (Or otherwise tell TypeScript about its members.)

declare var obj: any;
It seems to me that `any` should be the default type. Since type annotations are optional, it should assume the most generic case and generate no warnings unless we tell it that `obj` is a more specific type.
Oct 3, 2012 at 6:14 PM

This code

var obj = {};

should not infer obj to be of type `any`. It is obviously an object, and TypeScript should recognize it as such, and allow IntelliSense for object prototype methods like `hasOwnProperty`.

I think the problem is that while you're allowed to define arbitrary properties on a value with type `any`, you can't do so on an object. I think you should be able to define any properties on object, since that's what objects are for.

Oct 3, 2012 at 6:29 PM
peterolson wrote:

...

I think the problem is that while you're allowed to define arbitrary properties on a value with type `any`, you can't do so on an object. I think you should be able to define any properties on object, since that's what objects are for.

Good point, I suppose any would include some other types that wouldn't make sense here - such as undefined. Also, since other primitives like number, string, function, etc are simply objects they would also allow allow you to define arbitrary properties on them without warnings. This is my intention.

Oct 3, 2012 at 6:41 PM

I think only the following types should allow arbitrary properties defined without warnings:

  • Object
  • Function

String and Number primitives aren't actually objects. You can see that when you write code like this:

var a = "";
var b = 1;
a.x = "value";
b.x = "value";
console.log(a.x, b.x);

a.x and b.x will be undefined.

You can assign properties to an Array, but I adding non-indexed properties to an Array is kind of abusing Array.

Oct 3, 2012 at 6:50 PM
peterolson wrote:

...

String and Number primitives aren't actually objects. You can see that when you write code like this:

var a = "";
var b = 1;
a.x = "value";
b.x = "value";
console.log(a.x, b.x);

a.x and b.x will be undefined.

You can assign properties to an Array, but I adding non-indexed properties to an Array is kind of abusing Array.

Good catch. Forgot about that.

I think TypeScript should allow this behavior for any type that JS allows it for. If that includes Arrays then so be it, despite the fact that it is abuse. ;)