Creating a return type in Typescript Generics depending on the provided argument

Could you assist in creating a dynamic TypeScript return type based on whether an argument is undefined or not?

Here is a export interface ToObject<T> { [k: string]: T; } export const toObject = <T, V = (keyof T)>( list: T[], key: keyof T, valueKey?: V ): V extends keyof T ? ToObject<T> : ToObject<T[keyof T]> => valueKey === undefined ? list.reduce((all, cur) => ({ ...all, [cur[key] as unknown as string]: cur }), {} as ToObject<T>) : list.reduce((all, cur) => ({ ...all, [cur[key] as unknown as string]: cur[valueKey as unknown as keyof T] }), {} as ToObject<T[keyof T]>);

Usage :

interface Data{
  a: string;
  b: string;
  c: string;
}
const list: Data[] = [
  {a:'a', b: 'b', c: 'c'},
  {a:'1', b: '2', c: '3'}
];

// use 1
toObject<Data>(list, 'a');
// response
{
  {'a': {a:'a', b: 'b', c:'c'}},
  {'1': {a:'1', b:'2', c: '2'}},
}

// Use 2
toObject<Data>(list, 'a', 'b');
//response
{ {'a': 'b'}, {'1': '2'} }

ISSUE:

// use 1 ERROR -> Cant do this
const dataMap: ToObject<Data> = toObject<Data>(list, 'a');
// Type 'ToObject<Data> | ToObject<string>' is not assignable to type 'ToObject<Data>'.
// Type 'ToObject<string>' is not assignable to type 'ToObject<Data>'.
// Type 'string' is not assignable to type 'Data'.(2322)

// Use 2 ERROR -> Cant do this
const dataKeyMap: ToObject<string> = toObject<Data>(list, 'a', 'b');
// Type 'ToObject<Data> | ToObject<string>' is not assignable to type 'ToObject<string>'.
// Type 'ToObject<Data>' is not assignable to type 'ToObject<string>'.
// Type 'Data' is not assignable to type 'string'.(2322)

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

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

What causes me to create components with incorrect paths?

Can someone assist me with creating a new component in the dynamic-print folder instead of it being created in the app? Thank you ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

The specified function is not recognized within the HTMLButtonElement's onclick event in Angular 4

Recently diving into Angular and facing a perplexing issue: "openClose is not defined at HTMLButtonElement.onclick (index:13)" Even after scouring through various resources, the error seems to be rooted in the index page rather than within any of the app ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

Utilizing Typescript's conditional type to determine behavior based on the specific value of a string literal type

I'm currently figuring out how to define a conditional type in typescript based on a predefined string literal Let me walk you through an example to clarify. To provide some context, users are required to categorize data from images, where there are ...

Transform the code provided by bundleMDX into an HTML string specifically for RSS, all the while utilizing the mdx-bundler

I am currently working on developing an RSS reader and I need to convert the code returned by bundleMDX into a string. This is necessary so that I can utilize it with ReactDOMServer.renderToStaticMarkup(mdx) in my project. You can find a similar implement ...

Converting a generic object from snake_case to camelCase using TypeScript

Looking to create a function that can transform an object with snake case keys into one with camel case keys. How can this be achieved in TypeScript by typing the input object, but keeping the solution generic? type InputType = { snake_case_key_1: numbe ...

I aim to link a variable in a directive with a component

Each directive comes with its own functionality and specific features. It can be challenging to understand how to connect a variable from a directive to a component. This particular directive involves detecting x-axis and y-axis positions during mouse ev ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

How can I create a join for my initial column in TypeORM?

I am trying to figure out how to create a verification email for my users, but I'm having trouble understanding how to connect the UserToken table with the user's id in TypeORM. Can someone provide some guidance on this? @Entity({name: "use ...

"Loop through an array using forEach leads to a subscription that

I am a beginner in Angular and struggling to understand how async functions work. I have written the following code, but I am encountering an error: GET https://localhost:44353/api/ecams/id/undefined 400 and ["The value 'undefined' is not va ...

Unable to activate the AWS IoT security audit using CDK

I'm trying to activate the AWS IoT security audit using a CDK stack, but I'm encountering some issues. Initially, I referred to this documentation for the interfaceAuditCheckConfigurationProperty and implemented the following CDK code to enable ...

Is the Scope Staying Static in AngularJS 1.4 when Input Text Changes and Two-Way Binding is Enabled?

Encountering a strange issue with AngularJS 1.4 (TypeScript). The problem lies within the controller where a variable is set and displayed in an input text box. Oddly, when attempting to edit the value in this text box and clicking on a button, the variabl ...

Tips for comparing two typed objects using interfaces in React?

I am currently working in TypeScript and facing a challenge where I need to obtain the delta (key/value) of the modified attributes between two objects. Both objects are created using the same interface. export interface ITestObj { att1: string; att ...

Transforming JavaScript into TypeScript within an Angular 4 component class

Here is the Javascript code I currently have. I need to convert this into a component class within an Angular component. As far as I understand, the Character.prototype.placeAt() code is used to add a new method or attribute to an existing object. In this ...

Interfaces in Typescript

In my Angular 2 project, I am working on creating an interface for a complex object. Here is the code snippet of the object: // Defining the render state object this.aRenderState = { model: "", colour: false, showWireframe: false, showGrid: true, ...