简体   繁体   English

Typescript中的投放问题

[英]Casting issue in Typescript

I observed a piece of code which is not giving compile time or run time error but should give: 我观察到一段代码没有给出编译时间或运行时错误,但是应该给出:

message: string // this variable is of type string -- L1 <br>
abc: somedatatype //lets say abc is of some data type -- L2

message = <any> abc; // this should give error but does not -- L3 

I strongly believe this should give compile time error but it does not. 我坚信这应该会导致编译时错误,但事实并非如此。 Please clarify or suggest how we can get it corrected as it seems to be a serious issue. 请澄清或建议我们如何纠正它,因为这似乎是一个严重的问题。

Why should it throw a compile error when you explicitly cast it to any ? 当您将其显式强制转换为any时,为什么会引发编译错误? You are telling the compiler to trust you and do not type check. 您是在告诉编译器信任您,并且不要键入check。 See Type assertions 请参阅类型断言

Sometimes you'll end up in a situation where you'll know more about a value than TypeScript does. 有时,您会遇到比TypeScript更了解值的情况。 Usually this will happen when you know the type of some entity could be more specific than its current type. 通常,当您知道某个实体的类型可能比其当前类型更具体时,就会发生这种情况。

Type assertions are a way to tell the compiler “trust me, I know what I'm doing.” A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. 类型断言是一种告诉编译器“相信我,我知道我在做什么”的方法。类型断言就像其他语言中的类型转换一样,但是不执行任何特殊的数据检查或重组。 It has no runtime impact, and is used purely by the compiler. 它对运行时间没有影响,仅由编译器使用。 TypeScript assumes that you, the programmer, have performed any special checks that you need. TypeScript假定您(程序员)已经执行了所需的任何特殊检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM