I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class?

class Car {
    model: string;
}

let car:Car = new Car();
Object.keys(car) === [];

Is there a technique to make the model property of the Car class visible or accessible somehow?

Answer №1

In the previous comment, Aaron pointed out that in Javascript, public and private members appear the same, making it impossible to differentiate between them with a method. For example, consider the following TypeScript code:

class Car {
    public model: string;
    private brand: string;

    public constructor(model:string , brand: string){
        this.model = model;
        this.brand = brand;
    }
};

This code is compiled to:

var Car = (function () {
    function Car(model, brand) {
        this.model = model;
        this.brand = brand;
    }
    return Car;
}());
;

Upon compilation to JavaScript, it's evident that there is no distinction between the model and brand members, despite one being private and the other public.

To differentiate between private and public members, one could utilize a naming convention such as public_member and __private_member.

Answer №2

Here is an updated answer that includes Crane Weirdo's response regarding final JS public/private, which my original answer did not cover:

class Vehicle {
    axelcount: number;
    doorcount: number;

    constructor(axelcount: number, doorcount: number) {
        this.axelcount = axelcount;
        this.doorcount = doorcount;
    }

    getDoorCount(): number {
        return this.doorcount;
    }
}

class Trunk extends Vehicle {
    make: string;
    model: string;

    constructor() {
        super(6, 4);
        this.make = undefined; // forces property to have a value
    }

    getMakeAndModel(): string {
        return "";
    }
}

To use the code:

let car:Trunk = new Trunk();
car.model = "F-150";

for (let key in car) {
  if (car.hasOwnProperty(key) && typeof key !== 'function') {
      console.log(key + " is a public property.");
  } else {
      console.log(key + " is not a public property.");
  }

}

The output will be:

axelcount is a public property.
doorcount is a public property.
make is a public property.
model is a public property.
constructor is not a public property.
getMakeAndModel is not a public property.
getDoorCount is not a public property.

Below is the previous answer for comparison:

class Car {
    model: string;
}

let car:Car = new Car();

for (let key in car) {
  // only get properties for this class that are not functions 
  if (car.hasOwnProperty(key) && typeof key !== 'function') {
    // do something
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Personalizing Dialog Title in material-ui

While delving into the world of React and Material-UI, I encountered a challenge in updating the font color in the DialogTitle component. After browsing through various resources, I came across a helpful link that suggested overriding the dialog root class ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Issue encountered while developing custom Vuejs + Typescript plugin

In my index.ts and service plugin files, I have this structure: https://i.sstatic.net/Oh3Gq.png service.ts declare interface Params { title: string; description?: string; type?: string; duration?: number; } export default class ServiceToast { ...

Make an indirect mention of a distant JavaScript web address

Our company is looking to incorporate Rollup with Angular 4/Typescript and NPM, and we have a specific set of requirements: Various teams develop JS libraries that need to be centralized, similar to a CDN These libraries are hosted at remote URLs and sho ...

"Error: imports are undefined" in the template for HTML5 boilerplate

After setting up an HTML5 Boilerplate project in WebStorm, I navigate to the localhost:8080/myproject/src URL to run it. Within the src folder, there is a js directory structured like this: libraries models place.model.ts place.model.js addr ...

The button click function is failing to trigger in Angular

Within my .html file, the following code is present: The button labeled Data Import is displayed.... <button mat-menu-item (click)="download()"> <mat-icon>cloud_download</mat-icon> <span>Data Imp ...

Tips for using useState to update only the element that was clicked:

When I click the button to add a step to a chapter, it's adding a step to all chapters instead of just one. What mistake am I making? const example_chapters = [ { id: 1, title: 'Chapter 1'}, { id: 2, title: 'Chapter 2'}, ...

Setting key-value pairs in TypeScript objects explained

I encountered an issue with setting key/value pairs on a plain object. type getAObjectFn = <K extends string, V>(k: K, v: V) => Record<K, V> const getAObject: getAObjectFn = (k, v) => { return { [k]: v } } console.log(getAObject ...

What are the recommended techniques for utilizing prototypal and prototype-based inheritance in modern JavaScript (ES6) and TypeScript?

Some older discussions on Javascript prototypal inheritance & delegation can be found below: Benefits of prototypal inheritance over classical? classical inheritance vs prototypal inheritance in javascript I am curious about the current (2018) recom ...

Modify the variable value only in React when the state undergoes a change

I'm facing a situation where I need to reset the stocksHelper class and instantiate it again whenever the component renders based on a change in the stocks' useState. This is essential because upon a change in stocks, a calculation needs to be pe ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

I am unable to showcase the image at this time

Hey there, I'm having an issue with displaying an image stored inside the NextJS API folder. The alt attribute is showing up fine, but the actual image isn't displaying. When I console.log the image data, everything seems to be in place. Can anyo ...

Retrieve a HashMap through an HTTP GET request using Angular 10

I am currently using the following versions: Angular CLI: 10.0.1 Node: 12.18.2 OS: win32 x64 Angular: 10.0.2 In my setup, I have a Java Spring Boot service that is functioning correctly and returns data as a HashMap. Map<String, List<String>&g ...

Mastering the proper implementation of the factory method in TypeScript

Trying to articulate this question is proving to be a challenge, but I'll give it my best shot. In Sharepoint, a default ListItem comes with properties like id, title, createdby, createddate, modifiedby, and modifieddate. Custom lists can have addit ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...

Use the bind method to wrap console.log and preserve the calling context

When it comes to logging message text while preserving the original context (class, line number), console output does the job perfectly with console.log.bind(console). However, the challenge arises when I also need to send the message to an HTTP server for ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Error: Module not found '!raw-loader!@types/lodash/common/array.d.ts' or its type declarations are missing

I encountered a typescript error while building my NEXT JS application. The error message was: Type error: Cannot find module '!raw-loader!@types/lodash/common/array.d.ts' Below is the content of my tsConfig.json file: { "compilerOptions& ...

Issue: Import statement cannot be used outside a module in Appium

Encountering the following error while working on a colleague's laptop, so it appears that there is no issue with the code itself. It could be related to my local packages but I am not entirely certain. node version: v18.20.1 npm version : 10.5.0 impo ...