Retrieve the specific type of property from a generic data structure

I am currently working on a project where I need to determine the type of property within a given Type:

type FooBarType {
    foo: string,
    bar: number
}

The function would be structured like this:

getType<K extends keyof T>(key: K): string
. Therefore, calling the function with foo as the parameter should return string:

getType<FooBarType>('foo' as as keyof FooBarType) // string

At this stage, I do not have a concrete implementation for the generic, so using indexed access types may not be applicable?

Do you think this is achievable?

Here's what I have managed to put together so far:

getType <K extends keyof T>(key: K): string {
    type property = T[keyof T]
    // I am uncertain about how to proceed from here since utilizing T as a value seems restricted
}

MWE (Minimal Working Example):

type Config {
    database_host: string,
    database_pass: string | undefined,
}

const defaultConfig: Config = {
    database_host: 'host',
    database_pass: undefined
}

const config = ConfigBuilder<Config>.resolve(defaultConfig, new EnvironmentVars(), new YamlFiles(['../path/to/yaml']))

class ConfigBuilder<T> {

   public resolve(...): T {
     // key from default: string
     const configKey: keyof ConfigType = key as keyof ConfigType
     if (foundValues.hasOwnProperty(key.toUpperCase())) {
            config[configKey] = this.parse(configKey, foundValues[key]) 
     }
   }

   private parse<K extends keyof ConfigType>(key: K, value: any): ConfigType[K] {
        const type = this.getConfigKeyType(key)

        if (this.parserDictionary[type]) {
            return this.parserDictionary[type].parse(value)
        }

        throw Error(`Could not find parser for type ${type}`)
    }

    private getConfigKeyType<K extends keyof ConfigType>(key: K): string {
        type configItems = ConfigType[keyof ConfigType]

    }

}

// resulting in config object:
// {
//     database_host: 'host',
//     database_pass: 'pass'    
// }

It is possible that none or either of the environment variables or parsed files could provide the database_pass value.

Answer №1

To achieve this functionality, you can utilize the syntax FooBarType['foo'], as mentioned in a comment.

If you prefer to do it programmatically and include typings:

interface FooBarType {
    foo: string;
    bar: number;
}

const obj: FooBarType = {
   foo: '',
   bar: 1
}

function fetchValue<T, K extends keyof T>(obj: T, key: K): T[K] {
   return obj[key];
}

fetchValue(obj, 'foo'); // returns string value
fetchValue(obj, 'bar'); // yields number value

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 problem with MUI SwipeableDrawer not being recognized as a JSX.Element

Currently, I am implementing the SwipeableDrawer component in my project. However, an issue arises during the build process specifically related to the typings. I have made the effort to update both @types/react and @types/react-dom to version 18, but unf ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

How to extract the first initials from a full name using Angular TypeScript and *ngFor

I am new to Angular and still learning about its functionalities. Currently, I am developing an Angular app where I need to display a list of people. In case there is no picture available for a person, I want to show the first letters of their first name a ...

The issue arises when using NestJs with Fastify, as the code does not continue executing after the app.listen()

Greetings everyone, this is my inaugural question on this platform, so please forgive any oversights on my part. I have a query regarding my NestJs application configured to run with Fastify. Unlike Express, the code after the app.listen('port') ...

Angular data table is currently displaying an empty dataset with no information available

While attempting to display a data table in Angular JS, an issue arose where the table showed no available data despite there being 4 records present. Refer to the screenshot below for visual reference. This is the approach I took: user.component.ts imp ...

Utilizing TypeScript for enhanced Chrome notifications

I am currently developing a Chrome app using TypeScript (Angular2) and I want to implement push notifications. Here is the code snippet for my notification service: import {Injectable} from 'angular2/core'; @Injectable() export class Notificati ...

Is There a Comparable Feature to *ngIf in DevExtreme?

Currently, I am diving into the world of webapp development using DevExtreme. As a novice in coding, this is my first time exploring the functionalities of DevExtreme. Essentially, I am seeking guidance on how to display certain elements based on specific ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Typescript enhances the functionality of the Express Request body

I need help with the following code snippet: const fff = async (req: express.Request, res: express.Response): Promise<void> => {...} How can I specify that req.body.xxx exists? I want it to be recognized when I reference req.body.xxx as a propert ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

"Overcoming obstacles in managing the global state of a TypeScript preact app with React/Next signals

Hello, I recently attempted to implement a global app state in Preact following the instructions provided in this documentation. However, I kept encountering errors as this is my first time using useContext and I suspect that my configuration might be inco ...

Using Jimp to load a font and retrieve its Base64 representation

I am currently working in Angular with Jimp, attempting to overlay text onto an existing image. However, the image is not updating as expected. const Jimp = require('jimp') var _this = this; Jimp.read("assets/TimeLine.png").then(function ( ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

The data remains undefined even after being initialized in the constructor

My goal is to extract queryParams from a URL and leverage that information to resolve data in the following manner: data = { searchValue: null || undefined }; constructor(private http: HttpClient, private route: ActivatedRoute) { route.queryParams.su ...

Step-by-step guide on implementing Form.create in TypeScript and Ant Design with function components

Having trouble compiling my form created using Form.create(). The error message I'm getting is: Argument of type 'FunctionComponent<MyProps>' is not assignable to parameter of type 'ComponentType<{}>'. Type 'Fu ...

Here's a way to resolve the issue: ReactDOM.render() - TS2345 error: Cannot assign type '() => Element' to type 'ReactElement' in the argument

After tackling React-Router with Typescript, I encountered a typing issue that has me perplexed. Prior to this, I was using an older version of React and React-Router. But now, after updating to the latest builds using yarn, I'm facing this hurdle. ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

The combination of both fullWidth and className attributes on a Material-UI component

I am facing an issue with using both the className and fullWidth properties on a Material UI TextField component. It seems that when trying to apply both, only the className is being recognized. When I use just the className or just the fullWidth property ...

Unable to set up enzyme adapter

Currently, I am in the process of setting up the enzyme adapter for testing purposes. The code snippet that I have is quite straightforward: import * as enzyme from 'enzyme'; import * as Adapter from 'enzyme-adapter-react-16'; enzyme. ...

Utilizing a library that solely enhances the functionality of the Array object

I have a library with type definitions structured like this: declare global { interface Array<T> { addRange<T>(elements: T[]): void; aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => an ...