Kuro
Kuro

Reputation: 35

How to Declare a Variable for Later in a Component?

I have a component which has variables that don't get assigned till ngAfterViewInit. I want to use those variables outside the init as well, but I don't know how. (Below is what I was thinking, but its gives an error saying Type 'Map' is not assignable to type 'undefined')

    export class DummyComponent implements AfterViewInit {
      map = null;
      mousePosition = undefined;
  

      ngAfterViewInit(): void {


        this.map = new Map({
         target: 'map',
         layers: [layer],
         view: view
        });
      }

      update(){ this.map.on(...) => {...}}

Upvotes: 0

Views: 1534

Answers (1)

Igor
Igor

Reputation: 62228

That is a type safety error. By default a new angular project will create a tsconfig.json file with the setting strict to set to true. This, in turn, will control the setting noImplicitAny and have it set to true which means that if you do not constrain a variable/field instance explicitly it will be constrained to the assigned value's type.

As you assign map to null the default allowed type is now null as you did not define a type when you defined the field. You can solve by specify allowed types for the field map to include both null and Map.

map: Map | null = null;

Now either assignment will be allowed. Do keep in mind that in your code you must also assert the type for the field when you want to access it if multiple types are allowed. Example:

otherMethod(): void {
  if (this.map !== null) {
    this.map. // do something with the map field
  }
}

Upvotes: 1

Related Questions