Issue
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?
Solution
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?)
Answered By - John Weisz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.