Kuan Kuan - 1 month ago 13
TypeScript Question

Type casting not work in Typescript

All:

I am pretty new to TypeScript, I start with a book called Typescript Revealed (Pub Feb.2013), in Chapter2, there is one section called "Casts", which have one line code like:

var a : int = <int>SomeNumberAsAString;


When I tried that, I use:

var SomeNumberAsAString = "1000";
var a: int = <int>SomeNumberAsAString;


But compiler gives me error like:

hello.ts(2,8): error TS2304: Cannot find name 'int'.
hello.ts(2,15): error TS2304: Cannot find name 'int'.


I wonder how to do this cast, or is the specification of Typescript changes?

Thanks

Answer

(Pub Feb.2013)

That book is old. Its called number now.

var SomeNumberAsAString = "1000";
var a: number = <number><any>SomeNumberAsAString;

Also this assertion is very unsafe and I would not do this in production code. But it gets the point across :)

More

A more up to date book chapter on assertions : https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html