Kuan Kuan - 1 year ago 117
TypeScript Question

Type casting not work in Typescript


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?


Answer Source

(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 :)


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download