What is the method for obtaining the properties of a type as an array in Typescript?

In the given scenario:

class Foo {
    constructor(
        private one: string, 
        private two: string, 
        private three: string) {
    }
}

Is there a way to create an array containing the type's properties?

For example, I need to generate an array like:

['One', 'Two', 'Three']

It's important to note that I specifically require the properties to be extracted from the type itself, not from an instance. Otherwise, I could simply use Object.keys(instanceOfFoo).

Answer №1

To retrieve the keys, you can utilize the method Reflect.construct(). Afterwards, you can convert the keys to an array using Object.keys().

Keep in mind: if a key does not have a default value, it will not be generated, as demonstrated with four.

class Foo {
  constructor() {
    this.one = ''
    this.two = ''
    this.three = ''
    this.four
  }
}

console.log(Object.keys(Reflect.construct(Foo, [])))

Answer №2

When looking to retrieve the field names from a class, you can achieve this by utilizing the code snippet below:

const fieldNames = Object.keys(myObj) as Array<MyClass>;

I trust this information proves beneficial to you.

Answer №3

After transpilation, the code shown above will result in the following JavaScript code:

var Foo = (function () {
    function Foo(one, two, three) {
        this.one = one;
        this.two = two;
        this.three = three;
    }
    return Foo;
}());

To begin with, I would extract the constructor by using

const c = Foo.prototype.constructor
and then retrieve the argument names from there. You can refer to this thread for more information on how to achieve this dynamically.

Answer №4

To start, you must create an instance of const a = new Foo(); and then access it using Object.keys

class Foo {
    constructor(
        private one: string, 
        private two: string, 
        private three: string) {
    }
}

const a = new Foo();
console.log(Object.keys(a)); // ["prop"]

View the DEMO here

UPDATE: It's worth noting that if you aim to retrieve the type, it's not achievable as types are no longer accessible once the code is is compiled.

Answer №5

Examine all the keys within the Foo.prototype object

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

Diminish, then lead to a fresh page

I have encountered an issue with my code. The wrapper performs a fade out effect before redirecting the user to a URL. However, it only fades out once and I suspect this is due to the browser caching or loading the page quickly. Is there a way to ensure t ...

Choosing options using an enum in Angular 2

In my TypeScript code, I have defined an enum called CountryCodeEnum which contains the values for France and Belgium. export enum CountryCodeEnum { France = 1, Belgium = 2 } Now, I need to create a dropdown menu in my form using this enum. Each ...

Merge two JSON arrays without specifying which fields to combine explicitly

After converting two Excel sheets to JSON using an online tool, two separate JSON properties were created for each sheet. The resulting JSON example looks like this: { "Product Info": [ { // Product information details here }, ...

Dynamic loading of tinymce in progress

When tinymce is loaded in the head and before dom, everything works fine. However, if I attempt to load the JavaScript with ajax using jquery.getScript(), it doesn't work. I initialize tinymce when the user clicks the content area, so the dom must be ...

switch the visibility of the p tag based on its content

It seems like solving this shouldn't be too challenging, but I'm still learning when it comes to Javascript or JQuery. HTML: <p><span id="AddLine1Summary"></span>,</p> <p><span id="AddLine2Summary"></span& ...

AJAX request made to a specific local directory, instead of the usual localhost

Currently, I am working on a project to create a database that can be filtered using various options. My approach was to keep it simple by using HTML for sliders and checkboxes, along with JavaScript/jQuery for filtering the results. This setup allows me t ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

Angular - Set value only if property is present

Check if the 'rowData' property exists and assign a value. Can we approach it like this? if(this.tableObj.hasOwnProperty('rowData')) { this.tableObj.rowData = this.defVal.rowData; } I encountered an error when attempting this, specif ...

Identifying the completion of loading a HTML page using an object tag

I am trying to load an HTML page using an object tag, and once the page is fully downloaded, I want to display something. I have attempted the following approach, but it is not working: document.querySelector(".obj_excel").addEventListener("load", funct ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Determine if an object hierarchy possesses a specified attribute

When passing a set of options as an object like this: var options={ sortRules:[ {...}, // rule 1 {...}, // rule 2 // etc. ], filterRules:[ {...}, // rule 1 {...}, // rule 2 // etc. ], etc ...

Unable to access the variable field of MongoDB in JavaScript

I'm facing an issue while trying to loop through an array I retrieved from mongodb. It seems the array is treated as a single element, and here is the code snippet: const project = await Project.findOne({ embedId: inititalData.embedId }); console. ...

Using Angular 6 shortcodes in HTML

Is there a way to save an element in HTML as an alias for repeated use in Angular 6 without using *ngIf directive? For instance, consider the following code snippet: <dumb-comp [name]="(someObservable | async).name" [role]="(someObservable | a ...

Update the website's navigation key for improved user experience

Can the navigation key on a website be altered from 'Tab' to another key, such as 'Enter', allowing for the focus to shift to the next element with the corresponding 'tabindex' when the 'Enter' key is pressed? ...

Text that appears automatically in an input field

I've searched high and low, but I just can't seem to find a solution that works for me. What I need is a way to automatically populate a HTML text field with default text when the page loads. This default text should ideally be a PHP variable and ...

Creating a Typescript interface for a sophisticated response fetched from a REST API

I'm currently struggling with how to manage the response from VSTS API in typescript. Is there a way to handle this interface effectively? export interface Fields { 'System.AreaPath': any; 'System.TeamProject': string; 'Sys ...

Instead of displaying a regular text box, the output unexpectedly shows "Printing [object HTML

There are some HTML and JavaScript files that I have. I've written some functions in my JavaScript file to save the values of different input fields. However, when I try to print the description, it just displays [object HTMLInputElement]. This mak ...

Utilizing a function upon page initialization in VueX

I am currently learning Vue with Vuex and I have created a method called 'llamarJson' which is used to retrieve JSON data. However, I am facing difficulties in using this method when the page loads. I have tried various approaches but have not be ...

Pass the value from JavaScript to PHP

I am looking to insert a JavaScript value into PHP: var temp = $('#field_id').val().charAt(0); The 'temp' variable returns values ranging from 1 to 4. var value = "<?php echo $variable[temp]['id']; ?>"; How can I re ...

What advantages does utilizing an angular directive provide in the context of a comment?

Up to now, I have primarily used Directives in the form of Elements or Attributes. Is the Comment style directive simply a matter of personal preference for style? app.directive('heading', [function () { return { replace: true, ...