'How to access private json data on parent classname
I have this situation:
// constans.ts
export const options = {
sizes: ['foo', 'var']
}
// base.component.ts
class Base {
constructor(private _options: object) {}
public get options(): object { return this._options; }
}
// Child component
import { Base } from './base.component';
import { options } from './constants';
class Child extends Base {
constructor() {
super(options);
console.log(this.options); // <-- {sizes: Array(2)}
console.log(this.options.sizes); // <-- I CAN'T ACCESS TO .sizes
}
}
Why can't I access this.options.sizes array but I can see on console.log(this.options)?
I have this error:
TS2339: Property 'sizes' does not exist on type 'object'
Solution 1:[1]
You don't have access to the properties of the options object because you declared it of type object. If you use proper typing, it will be easier for typescript to help you with that:
export interface MyOptions {
sizes: string[];
}
// base.component.ts
class Base {
constructor(private _options: MyOptions) {}
public get options(): MyOptions { return this._options; }
}
// Child component
import { Base } from './base.component';
import { options } from './constants';
class Child extends Base {
constructor() {
super(options);
console.log(this.options); // <-- {sizes: Array(2)}
console.log(this.options.sizes); // <-- now it should work
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Octavian Mărculescu |
