打字稿类型转换不起作用 [英] Typescript type casting not working

查看:62
本文介绍了打字稿类型转换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对TypeScript很陌生。我从一本名为《 Typescript Revealed》(2013年2月出版)开始。在第二章中,有一个名为 Casts的部分,具有以下示例:

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;

我尝试应用以下示例:

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

但是编译器给了我一个错误:

But compiler gave me an error:


hello.ts(2,8):错误TS2304:找不到名称'int'。

hello.ts(2,15):错误TS2304:找不到名称' int'。

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

我想知道如何进行此类型转换,或者Typescript的规范已更改?

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

推荐答案


(2013年2月发布)

(Pub Feb.2013)

那本书是。现在称为 number

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 href = https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html> https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion .html

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

这篇关于打字稿类型转换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆