TypeScript Type Assertion question

I was reading through the Babylon.js source and found a way to do Type Assertion I haven’t seen before

For Type Assertion, I’ve always been doing something like:

const a = 'hi' as string;

But now I see that there’s another way that seems to accomplish the same thing:

const b = <string>'hi';

Would anyone know what this second approach is called? And if there are reasons to use one over the other?

Thank you :slight_smile:

Type casting.

The main difference is that assertion doesn’t change the type at runtime but it helps the compiler while checking the types, obviously at compile time.

Casting works at runtime and casts an object of one type to another type.

1 Like
  1. One doesn’t nees assertion in the first case. const a = 'hi' is enough to a to be recognized as string.
  2. The second case relates go Generics - Documentation - Generics
    Here is another good explanation - types - What does angle brackets “<>” mean in function declaration in Typescript? - Stack Overflow
2 Likes

Thank you both for your help, @roland and @labris !

Thanks for sharing the phrase “angle bracket”, which was super helpful when searching this

According to https://typescript-eslint.io/rules/consistent-type-assertions/, it seems that both of the following are Type Assertions and have the same effect:

const a = 'hi' as string;
const a = <string>'hi';

Source

TypeScript provides two syntaxes for “type assertions”:

  • Angle brackets: <Type>value
  • As: value as Type

This rule aims to standardize the use of type assertion style across the codebase. Keeping to one syntax consistently helps with code readability.

1 Like

The ‘as’ keyword has historical significance and was introduced because of the ambiguity of JSX expressions in TSX files.

1 Like

Also, “as” is simpler to type then “<>” :slight_smile:

1 Like