Search code examples
castingtypescript

Typescript type casting not working


I am pretty new to TypeScript. I started with a book called Typescript Revealed (Pub Feb.2013). In Chapter 2 there is a section called "Casts" that has the following example:

var a : int = <int>SomeNumberAsAString;

I tried to apply the example, as follows:

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

But compiler gave me an error:

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

I'm wondering how to do this cast, or has the specification of Typescript changed?


Solution

  • (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 https://basarat.gitbook.io/typescript/type-system/type-assertion