Mark
Mark

Reputation: 626

Casting issue in Typescript

I observed a piece of code which is not giving compile time or run time error but should give:

message: string // this variable is of type string -- L1 <br>
abc: somedatatype //lets say abc is of some data type -- L2

message = <any> abc; // this should give error but does not -- L3 

I strongly believe this should give compile time error but it does not. Please clarify or suggest how we can get it corrected as it seems to be a serious issue.

Upvotes: 2

Views: 73

Answers (1)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

Why should it throw a compile error when you explicitly cast it to any? You are telling the compiler to trust you and do not type check. See Type assertions

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually this will happen when you know the type of some entity could be more specific than its current type.

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

Upvotes: 3

Related Questions