Typescript中的类型推断与显式类型声明 [英] Type inference vs. explicit type declaration in Typescript

查看:251
本文介绍了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 = falsename: 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中的类型推断与显式类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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