Modify the data type of an object member based on its original type

I am seeking to convert the data type of each member in an object based on the specific member variable.

Here is an example:

class A {
    fct = (): string => 'blabla';
}

class B {
    fct = (): number => 1;
}

class C {
    fct = (): { obj: string } => ({
        obj: 'la'
    });
}

export const Contracts = {
    a: A,
    b: B,
    c: C
};

type myContracts = typeof Contracts;

type MySuperType<T> = {
    [P in keyof T]: string;
};

type a = MySuperType<myContracts>;

The snippet provided yields:

type a = {
    a: string;
    b: string;
    c: string;
}

Desired output:

type a = {
    a: string;
    b: number;
    c: { obj: string };
}

Answer №1

Create a custom type called MySuperType that enforces the requirement for objects to have values of a specific class, where instances of this class must contain a property named fct which is a function. Obtain the individual instances by using the InstanceType utility and then extract the return type of the functions using the ReturnType utility.

type FunctionClass = {
  new(): { fct: (...args: unknown[]) => unknown}
}
type MySuperType<T extends Record<string, FunctionClass>> = {
    [P in keyof T]: ReturnType<InstanceType<T[P]>['fct']>;
};

type example = MySuperType<myContracts>;

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

Tips on incorporating esbuild extensions in the template.yaml file of AWS SAM

Currently, my TypeScript Lambda functions are managed using the AWS Serverless Application Model (SAM), and I rely on esbuild for the build process. I'm interested in incorporating esbuild plugins into my build process to enable support for TypeScrip ...

What is causing the error "has no properties in common with" in this wrapped styled-component?

When looking at the following code, Typescript is flagging an error on <HeaderInner>: [ts] Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & Pick & Partial>, "className"> & ... ...

Utilizing Material UI and TypeScript to effectively pass custom properties to styled components

Currently, I am utilizing TypeScript(v4.2.3) along with Material UI(v4.11.3), and my objective is to pass custom props to the styled component. import React from 'react'; import { IconButton, styled, } from '@material-ui/core'; con ...

Managing a MySQL database in NodeJS using Typescript through a DatabaseController

I'm currently working on a restAPI using nodejs, express, and mysql. My starting point is the app.js file. Within the app.js, I set up the UserController: const router: express.Router = express.Router(); new UserController(router); The UserControll ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...

Troubleshooting Problem in Angular 6: Difficulty in presenting data using *ngFor directive (data remains invisible)

I came across a dataset that resembles the following: Within my app.component.html, I have written this code snippet: <ul> <li *ngFor="let data of myData">{{data.id}}</li> </ul> However, when I execute this code, it only displa ...

Access PDF document in a fresh tab

How can I open a PDF file in a new tab using Angular 6? I have tried the following implementation: Rest controller: @RestController @RequestMapping("/downloads") public class DownloadsController { private static final String EXTERNAL_FILE_PATH = "/U ...

What steps should I take to successfully compile my Typescript Webpack project without any errors?

Currently, I am attempting to convert only two .js files into .ts files within my webpack node.js project and then compile them (actions.ts and flux.ts). When I execute the command: webpack --progress --colors I encounter the following errors: 'use ...

Ways to mandate a field to only be of type object in TypeScript

I need to design a type that includes one mandatory property and allows for any additional properties. For instance, I require all objects to have an _id property of type string. {_id: "123"} // This will meet the criteria {a: 1} // This will not work as i ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Issue with migrating TypeOrm due to raw SQL statement

Is it possible to use a regular INSERT INTO statement with TypeOrm? I've tried various ways of formatting the string and quotes, but I'm running out of patience. await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ...

Effortless Tree Grid Demonstration for Hilla

As someone who is just starting out with TypeScript and has minimal experience with Hilla, I kindly ask for a simple example of a Tree Grid. Please bear with me as I navigate through this learning process. I had hoped to create something as straightforwar ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

Is it possible to create an Angular 2 service instance without relying on the constructor method?

I'm struggling to utilize my ApiService class, which handles API requests, in another class. Unfortunately, I am encountering a roadblock as the constructor for ApiService requires an HttpClient parameter. This means I can't simply create a new i ...

What is the proper way to manage the (ion select) OK Button?

Hey there, I'm working with an Ionic select directive and I need to customize the functionality of the 'OK' button. When I click on it, I want it to call a specific function. I'm aware of the (ionChange) event, but that only triggers w ...

Tips for guaranteeing the shortest possible period of operation

I am in the process of constructing a dynamic Angular Material mat-tree using data that is generated dynamically (similar to the example provided here). Once a user expands a node, a progress bar appears while the list of child nodes is fetched from the ...

What is the correct way to convert a non-observable into an observable?

Can I convert a non-observable into an observable to receive direct image updates without having to refresh the page, but encountering this error: Type 'EntityImage[]' is missing the following properties from type 'Observable<EntityImage ...