gpt4 book ai didi

typescript - typescript 中的类型转换问题

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:13 25 4
gpt4 key购买 nike

我观察到一段代码没有给出编译时或运行时错误,但应该给出:

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

我坚信这应该会导致编译时错误,但事实并非如此。请澄清或建议我们如何纠正它,因为它似乎是一个严重的问题。

最佳答案

当你显式地将它转换为 any 时,为什么它会抛出一个编译错误?您告诉编译器信任您并且不进行类型检查。参见 Type assertions

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. 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 - typescript 中的类型转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com