javascripttypescriptknockout.jsecmascript-6modifiers

Object.keys returns private properties


I have class/viewModel created with Typescript. I made one field in this class as private in order to skip it when I try to get all other class properties.

Is it right and how can I skip my private property?

Object.keys(myObject).forEach(property => {
        //some stuff
     }
});

Example of my class :

class MyModel{
    id: any = ko.observable('');
    name: any = ko.observable('');

    address: any = ko.observable('');
    city: any = ko.observable('');
    state: any = ko.observable('');
    country: any = ko.observable('');

    private secretField= ko.observable('');
}

Solution

  • private keyword affects only visibility in TypeScript and doesn't affect JS output.

    For class properties that weren't defined on the prototype and thus can't be modified with class property decorators, the most straightforward way is to use _ naming convention for private properties:

    class MyModel {
        // ...
        private _secretField = ko.observable('');
    }
    
    Object.keys(myObject)
        .filter(key => !(typeof key === 'string' && key.charAt(0) === '_'))
        .forEach(property => {
            // some stuff
        });