How to set return types when converting an Array to a dynamic key Object in Typescript?

Can you guide me on defining the return type for this function?

function mapArrayToObjByKeys(range: [string, string], keys: { start: string; end: string }) {
  return {
    [keys.start]: range[0],
    [keys.end]: range[1]
  }
}

For instance:

mapArrayToObjByKeys(['a', 'b'], { start: 'beginning', end: 'ending' })

I'm looking for intelligent code suggestions like 'beginning' and 'ending' in vscode.

Answer №1

In cases where keys are flexible and not fixed, you can specify the return type as:

type dynamicObjReturnType = {
    [key: string]: string;
}

You can then use it in a function like this:

function createDynamicObject(keys: { key1: string; key2: string }): dynamicObjReturnType {
  return {
    [keys.key1]: 'value1',
    [keys.key2]: 'value2'
  }
}

If the keys are known to be fixed as 'key1' and 'key2', they can be directly included in the type definition:

function createFixedObject(keys: { start: 'key1'; end: 'key2' }): dynamicObjReturnType {
  return {
    [keys.start]: 'value1',
    [keys.end]: 'value2'
  }
}

type fixedObjReturnType = {
    key1: string;
    key2: string;
}

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

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

react-router: The 'history' type is not found in the current context

Here is some code snippet from App.tsx: interface AppProps{ history: any } export default class App extends React.Component<AppProps,...> { public state = { target: this.props.history.push('/') }; private route() { if (! ...

Using a function to reset a radio button selection in Ionic

Currently, I am in the process of developing an ionic app that includes a radio list on one of the pages. However, I have encountered an issue where the radio list does not clear when I navigate to the next screen and then return, resulting in a poor user ...

The refresh function in the table is not working as expected when implemented in a functional component. The table being used is Material

I am currently utilizing MaterialTable from https://material-table.com/#/docs/features/editable to manage data and perform CRUD operations within my application. I am seeking a way to automatically refresh the table data after any CRUD operation (add, upda ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Is there a way to enhance the functional purity by creating a single function that subscribes and returns a

I'm currently developing a project that involves receiving humidity data from a raspberry pi sensor connected to a backend. Within my Angular Component, I am aiming to display this data in a functional and pure manner. However, I have some doubts rega ...

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Difficulty Converting Array of Objects to Proper Type with Q.Promise and KO.mapping

I have encountered an issue while trying to filter an observable array. It seems that the ko.utils.arrayFilter method is converting all my model's field names to lowercase, causing unexpected behavior. I should mention that this project involves Types ...

Enabling Javascript compilation while overlooking typescript errors

Currently, I am working in VS Code with create-react-app using TypeScript. Whenever there are type errors, they show up in the browser and prevent compilation by TypeScript. I am looking for a way to only see these errors in the Google console and termin ...

The @Input directive is failing to receive any data from its parent component

Recently, I delved into the workings of Angular's @Input feature and have found it quite useful thus far. My database is Firebase, and the data snippet I am fetching looks like this: { "page_area_business_image" : { "expand" : { ...

Accessing Properties or Methods in Angular2 Components

My application consists of 3 main components: PageMenu, LoginSession, and LoginForm. The purpose is to establish a connection between the variables in LoginSession and PageMenu, allowing for the proper functionality of the LoginForm component. PageMenu: ...

Using Typescript to iterate through an array of objects and modifying their keys using the forEach method

I have an object called 'task' in my code: const task = ref<Task>({ name: '', description: '', type: undefined, level: 'tactic', participants: undefined, stages: undefined, }); export interface Tas ...

Determine data type based on key of object within a Zod array

Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object. To illustrate the issue: const obj = z.object({ nestedArray: z.array(z.object({ valueIWant: z ...

angular directive to receive an object

When I have a table and click on a row, the information is supposed to be displayed in a different component using the @input decorator. However, instead of displaying the correct result in my other component, I am getting [object Object]. table.html < ...

Production environment experiencing issues with Custom Dashboard functionality for AdminJS

I have successfully integrated AdminJS into my Koa nodejs server and it works perfectly in my local environment. My objective is to override the Dashboard component, which I was able to do without any issues when not running in production mode. However, wh ...

Is there a way to delete a wrapper (parent element) in Angular without deleting the child element as well?

The solution provided in this answer on Stack Overflow addresses jQuery and not Angular or TypeScript. My inquiry bears resemblance to this question raised on a forum, but I am specifically looking for a resolution within the context of Angular. Is there ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

The 'Event' type is lacking the specified properties when compared to the 'CdkDragDrop<string[], string[]>' type

After exploring the reorderable columns demo on stackblitz, I came across this interesting code snippet. Specifically, here is the HTML snippet: <table mat-table [dataSource]="dataSource" cdkDropList cdkDropListOrientati ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

I am searching for the vector geometric shapes svg elements that are commonly utilized in design editors. Can you point

When it comes to design editors, there are plenty of options such as Canva, Vistacreate, and Adobe Express. Each one uses a variety of styles for elements/objects/shapes. Are there any databases where I can find these resources? Some popular places include ...