I am using the Google Maps API in my project
I am getting an undefined error for my code:
export class AppComponent {
startLocation: string;
endLocation: string;
maneuvers: any[];
constructor(private mapQuestService: MapQuestService) {}
getDirections() {
this.mapQuestService.getDirections(this.startLocation, this.endLocation).subscribe(data => {
this.maneuvers = data.route.legs[0].maneuvers;
});
}
}
This is the error:
[{
"resource": "/c:/xampp/htdocs/CS701/hw5-part1/src/app/app.component.ts",
"owner": "typescript",
"code": "2564",
"severity": 8,
"message": "Property 'startLocation' has no initializer and is not definitely assigned in the constructor.",
"source": "ts",
"startLineNumber": 10,
"startColumn": 3,
"endLineNumber": 10,
"endColumn": 16
},{
"resource": "/c:/xampp/htdocs/CS701/hw5-part1/src/app/app.component.ts",
"owner": "typescript",
"code": "2564",
"severity": 8,
"message": "Property 'endLocation' has no initializer and is not definitely assigned in the constructor.",
"source": "ts",
"startLineNumber": 11,
"startColumn": 3,
"endLineNumber": 11,
"endColumn": 14
},{
"resource": "/c:/xampp/htdocs/CS701/hw5-part1/src/app/app.component.ts",
"owner": "typescript",
"code": "2564",
"severity": 8,
"message": "Property 'maneuvers' has no initializer and is not definitely assigned in the constructor.",
"source": "ts",
"startLineNumber": 12,
"startColumn": 3,
"endLineNumber": 12,
"endColumn": 12
}]
I’m honestly not sure where I need to define other then the app.component.ts file.
2
Answers
Each
this.something
call refers to a variable of the class in which it is located, in this case AppComponent. This means each variable such asstartLocation
must be declared first with the corresponding ts type.For example this would declare a
name
variable to which you could refer withthis.name
in a function.Keep in mind the type must match every possible return value of the service so be sure to check the code of the service or just base it off the error messages coming up with the type set up incorrectly.
Lastly it looks like you’re using one or more of the variables as an input value, despite the fact you have never declared what the value should be.
You get these error messages because
strictPropertyInitialization
in thetsconfig.js
is set to true. This requires any properties of a class to be initialized when they’re declared OR inside the constructorOR you can use the
!
when defining the property to bypass thestrictPropertyInitialization
on a per case basis.And if you don’t want the strict property initialization checking at all you can change that option in the
tsconfig.json
file.https://www.typescriptlang.org/tsconfig#strictPropertyInitialization