In Typescript there is two way to cast objects.
<type>variable
and
variable as type
Both of these seems to be permanent (compile-time) casting so the casted object will retain it's type. E.g:
let number: number = 2;
let string1 = <string>number;
let string2 = number as string;
string1; // -> the type is string
string1; // -> the type is string
My question: What is the difference between the two?
They are both the same. the foo as string syntax was introduced to avoid ambiguity with JSX syntax (commonly used with React).
More information here
What is the difference between the two?
They are identical. x as Y was later created as an alternative syntax for <Y>x to enable non-ambiguous type-assertions in TSX files (as <Y>x would be otherwise recognized as a JSX expression). The x as Y syntax is preferred.
However, you have an apparent misconception here. This is not type-casting, but a compile-time type-assertion. The difference between the two is best demonstrated by what happens at runtime:
let number: number = 2;
let string = number as string;
console.log(typeof string); // "number"
TypeScript does not have a runtime framework to do automatic type-casting and type-checking, this is a design goal. (seriously?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With