Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between type assertions and the newer `as` operator in TypeScript?

People also ask

What is type assertions in TypeScript?

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.

Is type assertion bad TypeScript?

It weakens Type Safety Because of this, type assertions are considered an anti-pattern or code smell unless the user is absolutely sure what they are doing. For example, in some advanced/fancy use case of type hacking, tooling or when the typings of a third-party library is not accurate.

What is as in TypeScript?

The as keyword is a Type Assertion in TypeScript which tells the compiler to consider the object as another type than the type the compiler infers the object to be.

What is type casting in TypeScript?

Typecasting, commonly known as type conversion, is a technique for transforming one type into another in TypeScript. Typecasting exists, even though they don't work in the same way in strong programming languages. It exists in Object-oriented programming, but it does not exist in JavaScript.


The difference is that as Circle works in TSX files, but <Circle> conflicts with JSX syntax. as was introduced for this reason.

For example, the following code in a .tsx file:

var circle = <Circle> createShape("circle");

Will result in the following error:

error TS17002: Expected corresponding JSX closing tag for 'Circle'.

However, as Circle will work just fine.

Use as Circle from now on. It's the recommended syntax.


From Wiki page: "What's new in TypeScript [1.6]":

New .tsx file extension and as operator

TypeScript 1.6 introduces a new .tsx file extension. This extension does two things: it enables JSX inside of TypeScript files, and it makes the new as operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator). For example:

var x = <any> foo; 
// is equivalent to:
var x = foo as any;