title: TypeScript: Implicit cast from any to everything?
body: <p>I'm just learning TypeScript and I'm a bit perplexed about the nature of <code>any</code>. Take a look at this:</p>
  
  <pre><code>var x: any = 1;
  var y = 1;
  x = y;
  y = x; // why does this not cause a compile-time error?
  </code></pre>
  
  <p>At first I understood <code>any</code> to be the type without any promises - which is why the first assignment is reasonable to work - but it appears that in other contexts (the second assignment), it can be a type with <em>all conceivable</em> promises.</p>
  
  <p>For example, this piece of insanity also compiles just fine:</p>
  
  <pre><code>undefined.foo
  </code></pre>
  
  <p>That's because <code>undefined</code> is assumed to be <code>any</code>, which is a type promising everything. Hmmm.</p>
  
  <p>Contrast this to</p>
  
  <pre><code>var a : HTMLElement = new HTMLDivElement();
  var b = new HTMLDivElement();
  a = b;
  b = a; // doesn't compile. phew.
  </code></pre>
  
  <p>Here we get what I would expect from assigning a more general thing to a more special thing in a strongly typed language: An error, as an explicit cast would be necessary:</p>
  
  <pre><code>b = &lt;HTMLDivElement&gt;a; // ah, you mean it's really a div...
  </code></pre>
  
  <p>In most cases where <code>any</code> is used, I would expect something like <code>unknown</code>, defined as</p>
  
  <pre><code>interface unknown { }
  </code></pre>
  
  <p>would be a better choice.</p>
  
  <p>I first came across this problem as my code was using <code>eval</code> to parse json. <code>eval</code> returns <code>any</code>, which means that TypeScript thinks that you can do everything with it, without any casts.</p>
  
  <p>I think that's clearly wrong. Compare that issue to factories in other typed languages, such as C#:</p>
  
  <pre><code>(MyType)Activator.Create(typeof(MyType)) // cast is needed
  </code></pre>
  
  <p>Or C++:</p>
  
  <pre><code>// cast is needed in C++ (not in C, though I think it really should...)
  (MyType*)malloc(size); 
  </code></pre>
  
  <p>Whenever I have a function that produces something untyped, I would expect that I need to cast it before I can use it for anything.</p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>Is there the analogous to <code>any</code>, something like the above <code>unknown</code>, that is standard?</li>
  <li>If so, why is <code>any</code> featured so prominently and the other so hidden?</li>
  <li>Has this issue been raised somewhere? Is there a discussion anyone can link to?</li>
  </ol>