Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

typescript - What is the difference between using the colon and as syntax for declaring type?

What is the difference between the : syntax for declaring type

let serverMessage: UServerMessage = message;

and the as syntax

let serverMessage = message as UServerMessage;

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One is a type annotation one is a type assertion.

The type annotation tells the compiler check that the assignment is fully valid and that message is indeed compatible with 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:

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...