Is it possible to generate an array of strings from the keys of a type or interface?

Imagine a scenario where we have a type or interface defined as NumberLookupCriteria:

type NumberLookupCriteria = {
  dialCode: string;
  phoneNumber: string;
}

or

interface NumberLookupCriteria {
  dialCode: string;
  phoneNumber: string;
}

Is there a way to extract all the keys from this structure and store them in a JavaScript array like this:

const keys = ['dialCode','phoneNumber']

Any suggestions on how to achieve this?

Answer №1

It is not possible because types and interfaces do not exist at runtime.

A potential solution could be using a class instead.

View TypeScript playground

class NumberLookupCriteria {
    constructor(
        readonly dialCode: string ="",
        readonly phoneNumber: string ="",
    ) {}
}

const arrayKey = (Object.keys(new NumberLookupCriteria()))

console.log(arrayKey) // ["dialCode", "phoneNumber"]

const test: NumberLookupCriteria = {
  dialCode: "a",
  phoneNumber: "b"
} 
// OK

const test: NumberLookupCriteria = {
  dialCode: "a"
} 
// KO: Property 'phoneNumber' is missing in type '{ dialCode: string; }' but required in type 'NumberLookupCriteria'

There are several discussions on this topic:

Get keys of a TypeScript interface as an array of strings
Get Type keys in TypeScript

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

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it ...

I'm trying to determine which jQuery event would be more beneficial for my needs - should I go with

I'm facing a dilemma On my website, I need to capture the value of a span within a modal. The value changes when the modal is opened and reverts to the old value when closed. This particular value represents the cart total in my online store. Wheneve ...

Show off beautiful text using a styled pre component in a React application

I've been attempting to highlight specific text within a React pre element, but unfortunately, it doesn't seem to be working as expected. Instead of displaying the highlighted text, it shows [object Object]. const Text = styled.pre ` col ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

converting the names of files in a specific directory to a JavaScript array

Currently working on a local HTML document and trying to navigate through a folder, gathering all the file names and storing them in a JavaScript array Let's say I have a folder named Videos with files like: - VideoA.mp4 - VideoB.mp4 How can I cre ...

Can you provide a brief explanation for this bubble sort JavaScript code?

Can someone please explain to me what the line j<len-i is doing in this bubble sort code? I believe removing -i from that line will still make the program work properly, var arr=[3,5,4,7,8,9,30,0,-1]; function bubble_Sort(arr){ var len = arr.length, ...

Ensure that the jQuery Knob is set to submit any modifications only after the final adjustment

Utilizing jQuery Knob by anthonyterrien, I have configured the step to be 20. My goal is to transmit the knob's value to the server. The issue arises when the change function is triggered every time the user adjusts the knob using either a right or le ...

Exploring the Power of JQuery with Hover Effects and SlideToggle

I was struggling to keep the navbar displaying without it continuously toggling when my pointer hovered over it. I just wanted it to stay visible until I moved my pointer away. <script> $(document).ready(function(){ $(".menu-trigger").hover(funct ...

I have a parent DIV with a child DIV, and I am looking to use jQuery to select the last child DIV. The parent DIV has an

In my HTML code, I have a parent div called "allcomments_4" which contains several child divs with unique IDs (oneEntry), each with their own children. My goal is to locate and retrieve the content inside the last child of the parent node (lastComment) and ...

Experiencing a hiccup in React while attempting to play an mp3 file

My project includes the following code snippet, with an example mp3 file and npm package: https://www.npmjs.com/package/react-sound import React from 'react'; import Sound from 'react-sound'; class CustomSound extends React.Component ...

Sending multiple values with the same name via AJAX using PHP

I'm facing an issue with my code: <form method="post" id="result-image" name="result-image" action="" > <?php $i=1; foreach ($data as $key => $datas) { ?> <div class="col-md-2 thumb custom-size col-lg-3 col-xs-4"> ...

Invoke a bounded function within an Angular directive using the ng-click event

I was wondering if it's possible to invoke a bound function within a directive by clicking on a specific part of a div. Currently, I have a div with an inner div that acts as a button for expanding the main div. The larger div has a directive associat ...

utilizing the identical characteristics of the parent component

In order for the properties in InputGroup.js to be accessible as this.props in lower-level components like TextInput.js, Checkbox.js, I have created a simple component called InputComponent.js. In this component, I assign this.props to this.prpt so that it ...

Are ngFormModel characteristics subject to change?

I've been facing challenges while working with ngFormModel and dynamic properties from classes. Despite my efforts, I'm unable to update the ngFormModel when changing variables to reflect new values. You can see an example of this issue in the fo ...

Is there a way to identify the accurate or incorrect array element and modify the component color accordingly?

Upon reviewing the question alternatives, I encountered a problem where clicking on one of the buttons correctly indicated whether it was the correct or incorrect answer by changing its color. However, the issue is that all buttons are being affected by th ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

What could be causing my React child component to not update when changes are made to an array passed down in props after fetching new data?

My Profile.js component is responsible for fetching activity data related to a specific user from the URL parameter and updating the profileActivity state. This state is then passed down to my child component, ProfileActivity.js, where it should be display ...

Retrieve component information from the service

Incorporated within my component is a form that I'm utilizing with reactive form and my intention is to reach this form through my service. For example: const id = MyComponent.id and inside my component: @Output: public id: number = 7; ...