Get the data property from the interface and define the return type

In my function, I am trying to extract data from an object structured by an interface. I want this function to specifically resolve the property data from the data object. While it works when I have any as the return type, I believe there should be a more efficient approach where the return type will match the type of the property.

Here is my current approach: Check out my code here

https://i.sstatic.net/OL8xE.png

Currently, I am only getting back a union type of all properties of the interface, but I am aiming to return the type of the specific property I want.

Answer №1

To enhance reusability, consider making the getData function generic and utilizing the generic type for both the input argument and return value:

interface Information {
  name:string,
  id:number,
}

const data: Information = {
  name:"example",
  id:1,
};

function getData<T extends keyof Information>(property: T): Information[T] {
  return data[property];
}

const example:string = getData("name");

Click here for interactive demo

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

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

What is the method for retrieving the second type of property from an array of objects?

I have a collection of objects that map other objects with unique identifiers (id) and names (name). My goal is to retrieve the name corresponding to a specific id. Here is my initial approach: const obj = { foo: { id: 1, name: 'one' }, ...

[Vue warning]: The property "text" was accessed during rendering, however it is not defined on the current instance using Pug

Looking for some guidance from the Vue experts out there. I've recently started working with Vue and I'm attempting to create a view that verifies an email with a unique code after a user signs up. Right now, my view is set up but it's not c ...

Is there a way for Ionic to remember the last page for a few seconds before session expiry?

I have set the token for my application to expire after 30 minutes, and I have configured the 401/403 error handling as follows: // Handling 401 or 403 error async unauthorisedError() { const alert = await this.alertController.create({ header: 'Ses ...

Implementation of a function in Typescript that can be defined with a

I am currently diving into the Typescript specification and I'm facing a challenge in creating a functional implementation for describable functions. https://www.typescriptlang.org/docs/handbook/2/functions.html The provided example lacks completene ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

The geolocation feature is operational in the browser test, but it is not functioning properly on the

I am currently creating an application that requires accessing the user's location at a specific point in time. To achieve this, I have utilized the ionic native geolocation feature which communicates with the Google API for reverse geocoding. Everyt ...

To enhance VS IntelliSense and type checking in react-intl's FormattedMessage component, assign an id that aligns with a custom TypeScript interface

Due to the limitations of react-localization in terms of date and number formats, as well as its heavy reliance on a single developer, our team made the decision to transition to react-intl for a more stable long-term solution. Check out the contributors ...

Using MUI DatePicker and react-hook-form to implement a date picker in the format DD/MM/YYYY

I have developed a custom datePicker component that combines react-hook-form and Material UI. However, I am encountering an issue where the values are being displayed in the format: "2024-04-10T22:00:00.000Z" Below is the code snippet: import { Localizati ...

Toggle Button in Angular upon Form Changes

I am currently working on a bug that involves preventing users from saving data if they have not entered any information in the form. The form structure is as follows: private buildAddressPopupForm() { this.form = this.fb.group({ roles: [''], ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...

Refreshing the cache in SWR, but the user interface remains unchanged inexplicably - SWR hook in Next.js with TypeScript

I am currently working on a project that resembles Facebook, and I am facing an issue with the like button functionality. Whenever I press the like button, I expect to see the change immediately, but unfortunately, SWR only updates after a delay of 4-8 sec ...

Angular Material 2: Sidenav does not come with a backdrop

I'm encountering an issue with the SideNav component while developing a website using Angular 2. The SideNav has 3 modes, none of which seem to affect what happens when I open it. I am trying to make the backdrop display after opening. Even though t ...

What is the best way to locate every object based on its ID?

Currently, I am facing an issue where I have a list of IDs and I need to search for the corresponding object in the database. My tech stack includes Nodejs, Typescript, TypeORM, and Postgres as the database. The IDs that I am working with are UUIDs. ...

Issue with method assignment in extending Array class in Typescript

Currently, I am utilizing Typescript and Vue in my workflow, although the specific framework is not a major concern for me. I have been attempting to expand Array functionality in the following manner: class AudioArray extends Array<[number, number]&g ...

What's with all the requests for loaders on every single route?

I'm in the process of setting up a new Remix Project and I'm experimenting with nested routing. However, no matter which route I navigate to, I keep encountering the same error: 'You made a GET request to "/", but did not provide a `loader` ...

What does ngModel look like without the use of square brackets and parenthesis?

Can you explain the usage of ngModel without brackets and parentheses in Angular? <input name="name" ngModel> I am familiar with [ngModel] for one-way binding and [(ngModel)] for two-way binding, but I am unsure what it means when ngModel ...

Error TS2304: Unable to locate the word 'InputEvent'

While exploring the topic of whether TypeScript has type definitions for InputEvent, I experimented with using @types/dom-inputevent in my Angular 7 project. However, I kept encountering the error TS2304: Cannot find name 'InputEvent' whenever I ...

Can you explain to me the significance of `string[7]` in TypeScript?

As I was working in TypeScript today, I encountered a situation where I needed to type a field to a string array with a specific size. Despite knowing how to accomplish this in TS, my instincts from writing code in C led me to initially write the following ...

Is there a workaround for utilizing reducer dispatch outside of a React component without relying on the store?

Recently, I implemented a reducer in my project that involves using react, typescript and nextJS. I am wondering if there is a method to trigger the reducer outside of a react component, such as from an API service. While searching for solutions, most re ...