Search code examples
typescriptcastingtype-assertion

Why there are 2 different syntax of casting in typescript?


As long as I know, there are 2 type of syntax to cast in Typescript.

  1. Just using < and > to cast

    const a = <A>b;
    
  2. Using as statement to cast

    const a = b as A;
    

I guess generated code of 1 or 2 is completely same. And, there were no such a syntax to use as statement when I started to use Typescript. I guess as is new syntax in typescript.

But, there should be something reason to make new syntax. Why they needed these syntax? Is there something inconvenient if there was only 1 cast syntax?


Solution

  • As described here

    Originally the syntax that was added was <foo>.
    ...

    However there is an ambiguity in the language grammar when using <foo> style assertions in JSX:

    var foo = <string>bar;
    </string>
    

    Therefore it is now recommended that you just use as foo for consistency.