Jimi Jimi - 1 month ago 7
TypeScript Question

Typescript compiler error property does not exist on object

I'm receiving typescript errors 'property does not exist on object' from my typescript files. I've read a few posts regarding this but I'm still unsure how to implement the work around.

I have a JSON object has two properties, I unpack it so I can access both of the values directly, which works fine, it's just a compile time I receive the error.

payload: {
value1: '',
value2: ''
}


my private method is where the issues are coming through.

private update(respo : Object) : void {

if (respo.hasOwnProperty('value1') || respo.hasOwnProperty('value2')) {
(<FormControl>this.controlGroup.controls['ctrlone']).setValue(respo.value1);

(<FormControl>this.controlGroup.controls['ctrltwo']).setValue(respo.value2);
}
}


I tried to export an interface like the one below but I get a console error '? parameter not found'

interface responseObject {
value1?: string
value2?: string
}


Any help is appreciated. I'm using typescript 1.8.

Jimi.

Answer

Your issue appears to be with the type argument. Don't type that as Object. Though I'm not sure what the issue is with your interface (it might be that you are missing semicolons?)

This works for me:

interface responseObject {
    value1?: string;
    value2?: string;
}

class SomeClass {
    private update(respo : responseObject) : void {
        if (respo.hasOwnProperty('value1') || respo.hasOwnProperty('value2')) {
            (<FormControl>this.controlGroup.controls['ctrlone']).setValue(respo.value1);

            (<FormControl>this.controlGroup.controls['ctrltwo']).setValue(respo.value2);
        }
    }
}

When you type something as Object the only attributes that the compiler knows about are those that exist on Object. Making an interface is definitely the correct way to go about this (so good on you for that!) but in the future, the "workaround" you are probably looking for is type any.

Comments