How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below:

type Flags = {
  flag1: string,
  flag2: string,
  flag3: boolean,
  flag4: number
}

// const myFlags: Flags = {
//   flag1: 'value 1',
//   flag2: 'value 1',
//   flag3: true,
//   flag4: 12
// }

My goal is to create a function getFlag with this structure:

function getFlag(flag: keyof Flags): any { 
   // return myFlags[flag]
}

Instead of simply returning any, how can I determine and return the specific data type corresponding to the flag being passed into the getFlag function?

(for simplicity, let's assume the flag types are limited to boolean, string, and number, but the goal is still to extract the exact property type instead of boolean | string | number)

Answer №1

To enhance the functionality, modify the function to be generic so that it can accept any type of string for looking up the corresponding value on the object.

function fetchValue<T extends keyof Values>(key: T) { 
   return myValues[key]
}
const output = fetchValue('key1');

For further precision, consider using as const to return the exact type.

 const myValues = {
   key1: 'data 1',
   key2: 'data 2',
   key3: false,
   key4: 56
 } as const;

function fetchValue<T extends keyof typeof myValues>(key: T) { 
   return myValues[key]
}
const output = fetchValue('key1');

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

Encountering a problem with react-select in typescript when using react-use-form-state

Having a specific and tricky issue that I can't seem to solve right now. Our project has wrappers around certain Form controls to manage all the necessary setup code, and I'm currently facing an issue with the Select component wrapping the Selec ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Angular 11 Working with template-driven model within a directive

My currency directive in Angular 8.2 formats currency fields for users by using the following code: <input [(ngModel)]="currentEmployment.monthlyIncome" currency> @Directive({ selector: '[ngModel][currency]', providers: [Curr ...

What is preventing me from using property null checking to narrow down types?

Why does TypeScript give an error when using property checking to narrow the type like this? function test2(value:{a:number}|{b:number}){ // `.a` underlined with: "Property a does not exist on type {b:number}" if(value.a != null){ ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Update the function's argument type signature if the current argument is a function with properties

Looking for input on a potential title change, but for now, here are the details of my specific use case: I'm currently developing a library that facilitates executing methods remotely and accessing properties across serialized boundaries like those ...

It seems like the recent upgrade to yarn 2 has caused issues with typescript types, whereas the installation of the same project with yarn 1 was

Recently, I've been attempting to update a typescript monorepo to utilize yarn 2, but I've encountered an issue where typescript is struggling to recognize certain react props. This functionality was working fine in yarn 1.x, leading me to believ ...

Utilizing Enum Lowercase as Index Key Type in TypeScript

Is there a way in TypeScript to use the lower case of an enum as an index key type? I have an enum defined as: export enum NameSet { Taxi = 'Taxi', Bus = 'Bus', Empty = '', } I want to define an object with keys based o ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Conceal the HTML element within a subscription

Currently, I am utilizing Angular and have a checkbox that I need to toggle visibility based on the response of an API call subscription. The issue lies in a delay when trying to hide the checkbox (as it is initially set to visible). My assumption is that ...

Adding TypeScript definition file to an npm package: A step-by-step guide

Is it possible to include typescript definitions (.d.ts files) in a pure javascript project without using TypeScript itself? I'm struggling to find any information on how to do this directly in the package.json. ...

Experiencing a problem with updating records in angular?

angular version: Angular CLI: 9.0.0-rc.7 I have encountered an issue while trying to update a record. After clicking on the edit icon, I am able to make changes to the record in the form. However, when I click on the Edit Button, the record gets updated i ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: I have attempted to fix this issu ...

Using ReactJS with Material UI and applying styles with withStyles including themes in TypeScript

I've been working on converting the Material UI Dashboard into TypeScript. You can find the original code here: Material UI Dashboard One issue I'm encountering is that I am unable to define CSS styles within the withStyles function while export ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below: appendImage(item){ this.imageCompress.compressFile(item, 50, 50).then( result => { this.compressedI ...

Differences between useFormState and useForm in Next.js version 14

Currently, I am intrigued by the comparison between using the react hook useForm and the react-dom useFormState. The Nextjs documentation suggests utilizing useFormState, but in practice, many developers opt for the react hook useForm. I am grappling with ...

Error: Invalid connection string for ELF Lambda detected

Having an issue with a lambda function that connects to a remote MongoDB on an EC2 instance using TypeScript. While I can connect to the database locally, there is an ELF error when running in lambda. It seems to be related to mismatched binaries of npm pa ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...