Vishal Arora
Vishal Arora

Reputation: 81

Typescript Object type does not allow access to properties

i am trying to create a variable with Object type and initialised it with a property. but when i try to access that property it shows error 'Property ____ does not exist on type Object'. I had already searched for this and i found there are 3 type object , Object and {}. I can access my properties with {} but not with object and Object.

export class customDirective {
    configg:Object={
        qSelector:'.card-text'
    };
    @HostListener('mouseover') onmouseover(){
        var element =this.el.nativeElement.querySelector(this.configg.qSelector);
        this.ren.setElementStyle(element, 'display', 'block');
        this.isHovering = true;
    }
}

Upvotes: 0

Views: 722

Answers (2)

Aniket Avhad
Aniket Avhad

Reputation: 4145

Access property of object type using [ ]

i.e. this.configg['qSelector'] not this.configg.qSelector

export class customDirective {
    configg:Object={
        qSelector:'.card-text'
    };
    @HostListener('mouseover') onmouseover(){
        var element =this.el.nativeElement.querySelector(this.configg['qSelector']);
        this.ren.setElementStyle(element, 'display', 'block');
        this.isHovering = true;
    }
}

Upvotes: 1

fjc
fjc

Reputation: 5815

Object is an actual class: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object. It has certain properties defined, and qSelector is not one of it.

To define an arbitrary object that can have any properties set without TypeScript complaining, use the any type (or leave out the type definition altogether):

configg: any = {
    qSelector:'.card-text'
};

Upvotes: 0

Related Questions