Type inference vs. explicit type declaration in Typescript

angular, typescript

Solution

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

And avoid:

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.

Problem

I've come across several different instances of code where variables are declared with an explicit type even though the inferred type is obvious: Example: `loading: boolean = false` or `name: string = "John"` or `count: number = 0` etc. 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?

Original source