Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between <type>variable and variable as type in Typescript

Tags:

typescript

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?

like image 932
NoNameProvided Avatar asked Feb 21 '26 23:02

NoNameProvided


2 Answers

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

like image 61
yadejo Avatar answered Feb 24 '26 14:02

yadejo


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?)

like image 43
John Weisz Avatar answered Feb 24 '26 14:02

John Weisz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!