Learn how to define an array of member names in TypeScript for a specific type

Is there a way to generate an array containing the names of members of a specific type in an expression?

For example:

export type FileInfo  = {
    id: number
    title ?: string
    ext?: string|null
}
const fileinfo_fields = ["id","ext","title"];

I need to provide these field names as arguments to different methods for various types.

For instance:

const info = await api.get_info<FileInfo>(1234, fileinfo_fields);

This is necessary because managing multiple types with numerous fields can be error-prone.

Although type information is not accessible at runtime, I simply require a constant array that includes the member names.

Something along the lines of this, but I'm struggling to figure it out:

const fileinfo_fields = magic_extract_expression<FileInfo>; // ????

Do you know if achieving this is feasible in any way?

Answer №1

The terms "field names" within objects are referred to as keys. Each object contains a collection of "key-value" pairs. TypeScript allows you to access the keys of a certain type using the keyof operator.

For instance:

type FileInfo = {
    id: number
    title?: string
    ext?: string|null
}

let key: keyof FileInfo; // "id" | "title" | "ext";

If you need an array of keys, you can achieve it by doing the following:

const keys: (keyof FileInfo)[] = ["id", "title", "ext"];

To learn more about the keyof operator, check out the documentation in the TypeScript handbook.

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

Exploring the depths of Rx.ReplaySubject: Techniques for delaying the `next()` event

Confused Mind: Either I'm mistaken, or the whiskey is starting to take effect. (I can't rule out the possibility that I'm just going crazy. Apologies for that.) Assumption: My assumption was that ReplaySubject would emit a single value eve ...

Error with Array type encountered in Typescript's find method

I am encountering an issue with code that looks like this: type X = { test: number; x: number; }[]; type Y = { test: number; y: number; }[]; type Z = { test: number; z: number; }[]; export const testFunc = (arg: X | Y | Z) => { return a ...

Limiting querySelector to a specific React component: a step-by-step guide

Is there a way to target a specific DOM element within a React component to change its color using the ComponentDidMount method? Parent component export class ListComponent extends Component<...> { render(): ReactNode { return ( ...

'value' is connected to every single hook

Every time I try to save my work using any hook, the 'value' field changes automatically. This has been causing me a great deal of stress. I would be extremely grateful if someone could assist me with this issue. click here for image description ...

Employing multiple subscriptions within a function

I am facing an issue in my Angular application where I am trying to display a detailed summary of the sales for a specific drink using the DrinkDetailComponent. However, upon initializing the component, only one backend call is being made to retrieve infor ...

Tips for implementing a real-time search feature in Angular

I require assistance. I am attempting to perform a live search using the following code: when text is entered into an input, I want my targetListOptions array, which is used in a select dropdown, to update accordingly. The code runs without errors, but not ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

Implementing express-openid-connect in a TypeScript project

Trying to incorporate the express-openid-connect library for authentication backend setup with a "simple configuration," an issue arises when attempting to access the oidc object from express.Request: app.get("/", (req: express.Request, res: express.Respon ...

The React useEffect() hook causing an infinite re-render when trying to fetch all data regardless of

Recently, I've begun diving into React and utilizing the useEffect hook to fetch news and events from a database upon page load. However, when attempting to add a loading spinner, I encountered an unexpected infinite loop issue that has left me scratc ...

The issue persists in Angular 5 and asp.net MVC where the ID number continues to increase despite being deleted

Currently, I am using Angular 5 (VS CODE) for the front-end and asp.net mvc/entity framework (VS2017) for the back-end. My CRUD methods are functioning properly; however, I have encountered an issue where the ID of a newly created row keeps increasing even ...

What is the best way to efficiently filter this list of Outcome data generated by neverthrow?

I am working with an array of Results coming from the neverthrow library. My goal is to check if there are any errors in the array and if so, terminate my function. However, the challenge arises when there are no errors present, as I then want to destructu ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...

What is the best way to implement a <Toast> using blueprintjs?

Struggling without typescript, I find it quite challenging to utilize the Toast feature. This component appears to have a unique appearance compared to the others. Shown below is an example code. How would you convert this to ES6 equivalent? import { But ...

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Issue: The 'typeOf' function is not exported by the index.js file in the node_modules eact-is folder, which is causing an import error in the styled-components.browser.esm.js file in the node_modulesstyled

Every time I attempt to start running, there are issues with breaks in npm start (microbundle-crl --no-compress --format modern,cjs) I have attempted deleting node_modules and package-lock.json, then running npm i again but it hasn't resolved the pro ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

Explanation of Default Export in TypeScript

I recently started learning about JS, TS, and node.js. While exploring https://github.com/santiq/bulletproof-nodejs, I came across a section of code that is a bit confusing to me. I'm hoping someone can help explain a part of the code. In this project ...

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...