使用冒号和 as 语法来声明类型有什么区别? [英] What is the difference between using the colon and as syntax for declaring type?

查看:34
本文介绍了使用冒号和 as 语法来声明类型有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

: 声明类型的语法有什么区别

What is the difference between the : syntax for declaring type

let serverMessage: UServerMessage = message;

as 语法

let serverMessage = message as UServerMessage;

他们似乎至少在这个例子中产生了相同的结果

They seem to produce the same result in this example at least

推荐答案

一个是类型注解一个是类型断言.

One is a type annotation one is a type assertion.

类型注解告诉编译器检查赋值是完全有效的,并且message确实与UServerMessage

The type annotation tells the compiler check that the assignment is fully valid and that message is indeed compatible with UServerMessage

类型断言告诉编译器,我知道我在做什么,message 是一个 UServerMessage,不管你认为你知道什么,我有更多的信息和我最清楚.即使您使用类型断言,仍然会执行一些检查,因此您可能会看到双重断言 message as any as UServerMessage 例如,如果 message 的类型与 非常不兼容UServerMessage

The type assertion tells the compiler, I know what I'm doing, message is a UServerMessage, never mind what you think you know, I have more information and I know best. Some checks are still performed even if you use type assertions so you might see double assertions message as any as UServerMessage for example if the type of message is very incompatible with UServerMessage

与断言相比,您应该始终更喜欢类型注释.谨慎使用断言,并且仅在必要时使用.类型断言是一把锤子,可以将方钉放入圆孔中,有时很有用,但您可能会再看看自己在做什么以确保它是正确的.确保它不是:

You should always prefer a type annotation to an assertion. Use assertion with care and only if you have to. A type assertion is a hammer to get a square peg to fit into a round hole, useful at times but you might take a second look at what you are doing to make sure its right. Make sure it's not:

这篇关于使用冒号和 as 语法来声明类型有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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