Reputation: 5957
In an Angular 2 app, is it necessary (or even best practice) to set the type if I set the default value?
ex.) Option 1
export class SomeClass{
someVar: string = 'test';
}
Or this way:
ex.) Option 2
export class SomeClass{
someVar = 'test';
}
In the above code, which is best practice for specifying type and default value? Option 1 or Option 2?
Upvotes: 3
Views: 1244
Reputation: 1
type is necessary for compilation. the actual value can change at runtime. the best thing if you specify a type of the variable and if you don't know a type at compilation time you might use any
type. It's well described in the language guide for TypeScript language.
The variable can be initialized inline like in your code, or in constructor, or in the method/function. The default value should be determined at runtime if the variable is undefined
.
Upvotes: 3
Reputation: 705
Typescript will guess the type using type inference. I personally prefer the type to be specified for variables and properties, but use inference for constants.
Upvotes: 1