Todd Davis
Todd Davis

Reputation: 6033

Using a Getter in Angular 5 and Typescript

I'm having a problem setting up a Getter in a Typescript class, and could use some help understanding what I'm missing. I have a class like this:

export class Parameter {
    constructor(
        public dataType: string = '',
        public title: string = '',
        public index: string = '',
        public values: Value[] = [],
        public isValid: boolean = false;
    ) {}
}

Using this works fine.

The isValid property is currently being set externally, but it is based on the values stored in the "values" array. I was thinking it is silly and inefficient to set this value externally, instead I should just set isValid as a read-only property. Make sense? For purposes of this question, I'll just setup some simple logic. So here is the re-written Class.

export class Parameter {
    constructor(
        public dataType: string = '',
        public title: string = '',
        public index: string = '',
        public values: Value[] = []
    ) {}

        get isValid(): boolean {
          return false; 
    }
}

When I run the code and try to access isValid from an instantiated Parameter class (which worked fine in the previous example). Now when I examine the class, the isValid property is "undefined". I set a breakpoint in the Getter and the breakpoints never get hit. I must be defining this wrong, or misunderstanding what I'm trying to do here.

Can anyone please help me understand? Thanks!

EDIT: I changed the isValid() code to just return false because my example code was confusing people. Even with it just returning false, it still comes back as "undefined".

Upvotes: 0

Views: 2137

Answers (2)

djs
djs

Reputation: 1690

You need to instantiate your Parameter object, i.e., let p = new Parameter('foo', ...);.

Functions (including getters/setters) will be undefined if you simply cast from a JSON object:

// doesn't work. getter will be undefined.
let p: Parameter = {
    dataType: 'foo',
    ...
};

Upvotes: 0

SEY_91
SEY_91

Reputation: 1687

If this.dataType === 'datetime' is false the method will return undefined . You have to return false in this case.

get isValid(): boolean {
        if (this.dataType === 'datetime') {
            return this.values[0].value !== '';
        } 
return false;
    }

Upvotes: 1

Related Questions