NoNameProvided
NoNameProvided

Reputation: 8987

What is the difference between <type>variable and variable as type in 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?

Upvotes: 2

Views: 225

Answers (3)

Dmase05
Dmase05

Reputation: 1089

As quoted from Basarat Ali Syed's book, TypeScript Deep Dive:

as foo vs. <foo>

Originally the syntax that was added was <foo>. This is demonstrated below:

var foo: any
var bar = <string> foo; // bar is now of type "string"

However there is an ambiguity in the language grammar when using <foo> style assertions in JSX: var foo = <string>bar; </string> Therefore it is now recommended that you just use as foo for consistency.

TypeScript Deep Dive

Upvotes: 3

yadejo
yadejo

Reputation: 1968

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

Upvotes: 4

John Weisz
John Weisz

Reputation: 31932

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

Upvotes: 3

Related Questions