Typescript type casting not working

2020-08-09 08:10发布

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?

5条回答
ゆ 、 Hurt°
2楼-- · 2020-08-09 08:22

I've read @basarat's answer and decided to post my own since I strongly believe that there's still some room for explanation.

Be warned, <number><any> casting won't generate a number. In fact it will allow your code to be compiled (thus you'll pass all static typing checks) but it won't be a number in javascript. Consider this snippet of code:

let str = "1000";
let a: number = <number><any>str;
let b: number = parseInt(str); //or just let b = parseInt(str)

console.log(typeof a); // string
console.log(typeof b); // number

I hardly can imagine cases when a-case is beneficial compared to b-case. I'd go with just parseInt or parseFloat or Number, whatever fits more. <T><any> casting looks smart but you must be 100% sure what you are supposed to achieve by that idiom.

And in most cases you probably don't want to achieve that )

查看更多
相关推荐>>
3楼-- · 2020-08-09 08:28

Here is the cleanest way to do it.

const numberString = '1000';
const a: int = numberString as any;
查看更多
萌系小妹纸
4楼-- · 2020-08-09 08:29
const a: number = <number> +SomeNumberAsAString;

+SomeNumberAsAString converts the string value to the number.

<number> before +SomeNumberAsAString says to Typescript compiler that we need to cast the type of the value to type number.

查看更多
手持菜刀,她持情操
5楼-- · 2020-08-09 08:40

I prefer this variant

let SomeNumberAsAString = '1000';
let a = +SomeNumberAsAString;
console.log(a);

查看更多
一夜七次
6楼-- · 2020-08-09 08:41

(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

查看更多
登录 后发表回答