How to use GeolocationPosition correctly in TypeScript?
Asked Answered
C

2

6

We want to access the user's location using the Geolocation API.

This snippet works fine:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition((position: GeolocationPosition) => console.log(position));
}

VSCode also doesn't show any errors or warnings, but the Angular CLI throws this error:

Cannot find name 'GeolocationPosition'.
navigator.geolocation.getCurrentPosition((position: GeolocationPosition) => console.log(position));

The project is using the following things:

  • Angular 11.0.6
  • tslib 2.0.0
  • ts-node 8.3.0
  • tslint 6.1.0
  • typescript 4.0.2

Also strict type checking is enabled in Angular CLI

How to use this type and other types from that API correctly?

Cytaster answered 20/1, 2021 at 15:25 Comment(2)
Sometimes its easier to simply allow TS to infer the type navigator.geolocation.getCurrentPosition((position) => console.log(position));. This way TS will automatically set the type correctlySilica
But If I pass the value to a function, like this.log(position); and the method looks like this: log(position: GeolocationPosition): void { console.log(position); } I still need the type in the function definition. If I simply use log(position) { }, the compiler will say the type of position is missing and when I add :any the type is unknown in the method. Hope you understand my dilemma, @OwenKelvinCytaster
A
9

Running TypeScript in v4.0.x brings up Position as the typename, but that appears to have been renamed to GeolocationPosition in 4.1.x. Can't find any docs on why they did that. See: https://mcmap.net/q/968161/-angular-11-why-can-39-t-the-compiler-find-39-geolocationposition-39-during-compiling-quot-cannot-find-name-39-geolocationposition-39-quot.

Recommend updating to the latest version of Typescript (currently 4.2.3)

Augie answered 7/3, 2021 at 3:44 Comment(1)
Can confirm this.... thanks @AugieElroy
E
1

You should be able to use the native Position type:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition((position: Position) => console.log(position));
}
Elvia answered 22/1, 2021 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.