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

Display issues with deeply nested components

I'm facing an issue with displaying the third nested component. Expected: Hello App Component Hello Nest-A Component Hello Nest-1 Component Hello Test-Z Component Actual: Hello App Component Hello Nest-A Component Hello Nest-1 Component Why ...

After implementing rewrites, my dynamic routes in Next.js are no longer functioning as expected

This is the current structure of my project and it was working fine before I added rewrites to my project. https://i.sstatic.net/X989W.png -dashboard --admin --page.tsx ---[adminId] ---page.tsx --cars --page.tsx ---[carId] ---page.tsx -lo ...

Sharing properties between components

While this topic has been discussed extensively, I am still struggling with my specific example. In my setup, I have a react-select component nested within another component, which is then part of the larger App component. SubjectSelect.tsx export default ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...

Tips for determining the defaultValue type in React.context usage

'use client'; import { useState, createContext, useMemo } from 'react'; type MessageStatus = 'default' | 'success' | 'error'; export type MessageProps = { type: MessageStatus; payload: string; }; ty ...

Developing with Electron JS and TypeScript - Leveraging TS-Node in the primary process

Is there a way to modify the code below in order for the electron main process to utilize Typescript by using ts-node? "scripts": { "shell": "cross-env NODE_ENV=development electron ts-node ./app/main.ts" } ...

Guide to incorporating a pluck feature into TypeScript code

One task I face frequently is extracting specific properties from an object const obj = {a:1, b: 2, c: 3}; const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2} Unfortunately, achieving this task with type safety in TypeScript can be c ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

What is the best way to implement a hover delay for an element in Angular?

Here is an element I'm working with: <div (mouseenter)="enter()" (mouseleave)="leave()">Title</div> In my TypeScript file: onHover = false; enter() { this.onHover = true; // additional functionality... } leav ...

Guide on removing a key from an object in TypeScript

My variable myMap: { [key: string]: string[] } = {} contains data that I need to modify. Specifically, I am trying to remove a specific value associated with a certain key from the myMap. In this case, my goal is to delete value1 from myMap[Key1]. Despit ...

Styling the pseudo element ::part() on an ion-modal can be customized based on certain conditions

Looking for a solution regarding an ion-modal with specific CSS settings? I previously had the following CSS: ion-modal::part(content) { width: 300px; height: 480px; } Now, I need to adjust the height based on conditions: if A, the height should be lo ...

Utilizing AWS Amplify with TypeScript and TypeScript Lambdas for powerful web development

Currently, I am working on a project that involves a nextjs frontend with TypeScript and AWS Amplify for the backend. My intention is to write my Lambda functions in TypeScript as well. However, I have encountered an issue where I have one tsconfig.json fi ...

Issue encountered on server using next.js - FetchError: failed to process request for https://jsonkeeper.com/b/4G1G

Struggling to fetch JSON data from a link and destructure it for use on the website. I have a getStaticProps export function that extracts the data and I want to pass it into my default Home function to iterate through it. I have come across information ab ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

`Troubleshooting problem with debugging mocha tests in a TypeScript environment`

I'm currently facing an issue while trying to debug a mocha test. Despite my efforts in searching on Google and Stack Overflow, I have not been able to find a solution. The error message is as follows: TSError: ⨯ Unable to compile TypeScript: sour ...

What are the steps to integrate a database into my Next.js application?

While I was experimenting with integrating postgresql into a nextjs project, I encountered an error 405 when trying to create an account. Below is the error message in the browser console: page.tsx:14 POST http://localhost:3000/api/auth/ ...