我遇到过几种不同的代码实例,即使推断的类型很明显,变量也使用显式类型声明:
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中的类型推断与显式类型声明
发布评论