How can generics be utilized to automatically determine the second argument of my function based on the optional property of the first argument?

Struggling to make TypeScript infer the second argument based on the type of property "data" in the first argument? Looking for tips on setting up type DialogHavingData.


type DialogHavingData<T> = /* Need help with this part */
    'data' in T ? T['data'] : any;

class MyDialog {
    data: { 
        prop1: string;
        prop2?: string;
        prop3: {
            name: string;
            age?: number;
        }
    };
}

class MyDialog2 {
    // Data is optional
}

function createDialogFromClass<T = any, Y extends DialogHavingData<T>>(dClass: T, payload: Y) {
    // Implementation goes here...
}

// When MyDialog has a "data" property, the second argument should match its type
createDialogFromClass(MyDialog, {
    prop1: "my string",
    prop3: {
        name: "Test Name",
        age: 12
    }
    // It should prompt for prop1 and prop2 types
})

// Any value allowed as MyDialog2 doesn't specify the data property
createDialogFromClass(MyDialog2, null) 
createDialogFromClass(MyDialog2, {test: "My test dialog"});

Playground Link

Answer №1

In Typescript, understanding the structure of T and its properties can be challenging. To address this, a common behavior needs to be defined. An example approach could be:

type DialogStructure = { [key: string]: string | number } 
type DialogWithData = { data?: DialogStructure }

This setup accommodates all types that adhere to the specified structure, allowing for objects with any string key and either string or number values. By making the data attribute optional, TypeScript recognizes its potential absence using the ? operator.

For the implementation, consider:

createDialogFromClass<T>(classInstance: T extends DialogStructure): DialogWithData

Here, a dynamic object structure parameter is accepted, returning an instance of DialogWithData.

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

Absolute file path reference in Node.js

I'm working on a Node.js project using WebStorm IDE. Here's the structure of my project: The root folder is named "root" and inside are 2 folders: "main" and "typings". The "main" folder has a file called "foo.ts", while the "typings" folder co ...

Receiving real-time updates from an Angular 2 service

Having an issue with displaying user nicknames in Angular 2 using the User ID. When attempting to call the getUserName(userId) function from dashboard.component.html, which then triggers the auth0 service to retrieve the user profile, I am encountering con ...

deleting the existing marker before placing a new marker on the Mapbox

Upon the map loading with GeoJson data, I have implemented code to display markers at specified locations. It works flawlessly, but I am seeking a way to remove previous markers when new ones are added. What adjustments should be made for this desired func ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Using Angular with Cordova - How to troubleshoot using TypeScript files?

Currently in the process of debugging the application using source files written in Typescript. Despite attempting to debug with Chrome, I have been limited to only being able to debug the Javascript files generated by Cordova which has proven difficult. ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Error message "ERR_FILE_NOT_FOUND" displayed in Ionic Dailymotion iframe player

While viewing the app on a browser, the video player functions properly. However, when accessed on a phone, the following error occurs. I suspect that the issue lies in the 'file:' prefix, but I am unable to remove it using string.replace('f ...

At times, the Angular global variable may be found to be

I am facing an issue with a component that takes an @Input variable to build a local string in the ngOnChanges method. In my HTML, I have an *ngIf statement checking for this local variable. The problem arises when, even after confirming that the variable ...

How can I display JSON values without revealing the parent in Angular 5 and Ionic 3?

I am trying to extract values from JSON without the parent keys. Here is the JSON structure I have: [ { "companies": [{ "id": 1, "name": "Prueba", "company_number": "23423423A", "latitude": 241241.12, "lo ...

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

The issue with Angular's Mat Option selected values not functioning properly

We have a scenario where there are two form fields, and the second field needs to be disabled or enabled based on the selected value from the first field. The first field contains 5 values: 'a', 'b', 'c', 'd', ' ...

Encountered an error while trying to access a property in an array from a JSON

Why am I continuously receiving undefined error messages and how can I prevent them when attempting to read json data? Currently, I am delving into Angular and embroiled in a project that involves externally sourced json. Here's a snippet of the json ...

Declare a new variable with a specific data type in TypeScript

I'm working on creating a variable in my component of a specific type, as shown below. myrequest.model.ts export class MyRequest { public endValue: string; public yearEnd: string; } When importing the above into my component, I do the follow ...

Explore the functionality of Typescript unit testing in debug mode with the assistance of VSCode

I'm looking to debug my Typescript spec.ts file using vs-code. Typically, I run it from the terminal like this: npm run test:unit -- page.spec.ts But I want to add some console.log statements for debugging. Is there a way to do this in vs-code? When ...

The Angular Service code cannot be accessed

Currently, I am utilizing Local Storage in an Angular 5 Service by referencing https://github.com/cyrilletuzi/angular-async-local-storage. My goal is to retrieve data from storage initially. In case the value is not present, I intend to fetch data from fir ...

Is there a way to access variables stored within a Singleton object?

I'm currently working on creating a singleton to retrieve two variables from different components. These variables are defined in a component that always runs before the others. The issue I'm facing is that the Singleton instance isn't bein ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Prevent Angular 4 Component Reloading

I need my component to remain stable without reloading every time a new page is accessed. Currently, it reloads on each page change which disrupts the functionality. This issue is particularly evident in the Header section where there is a Marquee that rel ...