regna
August 12, 2024, 10:28pm
1
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
roland
August 12, 2024, 11:44pm
2
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
regna
August 13, 2024, 1:47am
4
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
labris
August 19, 2024, 1:29am
6
Also, “as” is simpler to type then “<>”
1 Like