This project is read-only.

Type-cast syntax

Topics: General
Jan 3, 2014 at 11:04 AM
Edited Jul 29, 2014 at 11:23 AM
Why does the type-cast operator look like as it does? What is the reason for it to not look the same as in Java, C#, etc.? This syntax makes it (almost?) impossible to add TypeScript support into JSX, Facebook's JavaScript XML syntax transform. See the discussion here:

More about JSX: "JSX: E4X The Good Parts"
Jan 3, 2014 at 2:22 PM
We don't actually have a type-cast operator. Did you mean the type assertion operator?
interface MyInterface { height: number; };
var x = <MyInterface> {height: 3};
The type assertion operator does look like the cast operator in other languages, though it works a bit differently. It checks to make sure the type is compatible in either direction, then we treat the expression as the type in the assertion.

Are you asking why didn't we use () instead of <>?

I suspect the issue here is that this would be perfectly valid JavaScript if MyInterface was also a value, making it ambiguous whether it was a function call or a type assertion:
var x = (MyInterface)({height: 3});
Jan 3, 2014 at 11:14 PM
Sounds reasonable. However, Greeter<string>("Hello, world") is perfectly valid JavaScript as well, which stopped nobody from adopting such syntax...
Jan 6, 2014 at 5:17 PM
Yup, that's true. I remember us doing quite a bit of searching through JavaScript to make sure we weren't going to break anything choosing that syntax.
Jan 9, 2014 at 5:19 PM
Is there a chance that this syntax (type assertion) will change?

While E4X was a failure, XML-like syntax extensions is a good and obvious idea, which perfectly might make it into some next ECMAScript version. But if it happens, it will be impossible to incorporate that syntax into TS because of type assertions.
Jan 10, 2014 at 3:35 PM
No, the chance is slim the syntax will change at this point. We're working on the last block of tasks for hitting 1.0.