Typescript中的类型推断与显式类型声明

编程入门 行业动态 更新时间:2024-10-20 13:41:06
本文介绍了Typescript中的类型推断与显式类型声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我遇到过几种不同的代码实例,即使推断的类型很明显,变量也使用显式类型声明:

I've come across several different instances of code where variables are declared with an explicit type even though the inferred type is obvious:

例如:loading: boolean = false或name: string = "John"或count: number = 0等

TSLint比推断类型更喜欢推断类型,所以我想知道这仅仅是一个样式问题吗?这些显式类型甚至在运行期间是否重要?

TSLint favors the inferred type over the explicit type, so I'm wondering is this just a stylistic issue? Do these explicit types even matter during runtime?

推荐答案

在您的示例中,它只是关于样式,因此,从编译角度看,它不会对您的代码产生影响.请注意,这是在变量值显式定义其类型的情况下使用的,这可能会使您的代码在从其他变量中重新赋值的情况下读取起来很复杂.

In your example it is just about style, hence, it has not impact to your code from compilation perspective. Be aware this is for the cases where the variable value explicitly defines its type, which might make your code complicated to read in cases of resigning values from other variables.

换句话说,您可能会做得更好:

In other words it might be better you do:

name: string = "John" bday: Date = "1980/01/10" //the compiler says there is an error

并避免:

name = "John" bday = "1980/01/10" //no compiling error, but it should be new Date("1980/01/10")

注意:未定义的类型将始终被视为任何类型.

Note: Undefined types will always be considered as any.

更多推荐

Typescript中的类型推断与显式类型声明

本文发布于:2023-05-29 23:08:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355079.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   推断   声明   Typescript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!