Determine the data type of an individual attribute within a collection of classes

I am working with a series of classes that have a body property defined within them. Here is an example:

class Foo {
  body: {foo: string}

  constructor(body: Record<string, string>) {
    this.body = { foo: body.foo }
  }
}

class Bar {
  body: {bar: string}

  constructor(body: Record<string, string>) {
    this.body = { bar: body.bar }
  }
}

These classes are then assigned to an object where they can be accessed by a string:

const pages = {
  'foo': Foo,
  'bar': Bar
} as const

I also have a union type that includes all the classes:

type Pages = typeof pages[keyof typeof pages]
// typeof Foo | typeof Bar

My goal is to create an object that references the types of the body properties from each class in the pages object. For example:

// The values for `fooBody` and `barBody` should be types here
{
  'fooBody': {foo: string},
  'barBody': {bar: string}
}

Playground

Answer №1

Transforming the pages into a type defined by name and constructor class can greatly simplify the process.

type PageType = {
  page1: Page1
  page2: Page2
}

type AllContents = {
  [Key in keyof PageType as `${Key}Content`]: PageType[Key]['content']
}

const allContents: AllContents = {
  page1Content: { page1: 'string' },
  page2Content: { page2: '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

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

Obtain multiple class instances through HTTP-Get in Angular

Initially, explaining this with my actual code can be confusing, so I'll simplify the issue using a smaller example. Imagine my project retrieves data from 2 tables on the server, employeeDetails and employeeNames. employeeNames: This table consists ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

Upgrade from using fetch to utilize await in order to achieve the same outcome

After transitioning a one-time fetch request code snippet to my API, I encountered the following: let response = await fetch(visitURL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization& ...

The implementation of race in React Redux Saga is proving to have negligible impact

I have implemented the following saga effect: function* loginSaga() { const logoutTimeoutCreationDate: string | null = yield localStorage.getItem('logoutTimeoutCreationDate'); let logoutTimeout: number; if (!logoutTimeoutCreationDate || + ...

The error message "localStorage is undefined in Angular Universal" indicates that the local

I have chosen to utilize universal-starter as the foundation of my project. Upon initialization, my application reads a token containing user information from localStorage. @Injectable() export class UserService { foo() {} bar() {} loadCurrentUse ...

Tips for navigating to a different route during the ngOnInit lifecycle event

How can I automatically redirect users to a specific page when they paste a URL directly into the browser? I would like users to be directed to the /en/sell page when they enter this URL: http://localhost:3000/en/sell/confirmation Below is the code I am ...

What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my cod ...

Improving the management of user input in Lit components

I am seeking a more efficient method to manage all inputs within my lit component while minimizing the code usage. I am also employing Typescript in this process, utilizing @change=${this.handleInput} for all input fields. Below is an example of how the ha ...

What is the function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

React Native bottom tab navigator not changing between tabs

Hi, I'm new to React Native and I think I might have a structural issue because I can't figure out what I'm doing wrong. I'm trying to create 4 tabs, but when I click on each tab, it doesn't take me to the next page. Nothing happe ...

Employing the keyof operator with the typeof keyword to access an object

What data type should be used for the key variable? I am encountering an error stating that "string" cannot be used to index the type "active1: boolean, active2". const [actives, setActives] = React.useState({ active1: false, active2: false, }); con ...

Encountering issues in d3.js following the transition to Angular 8

After upgrading my Angular 4 app to Angular 8, I encountered an issue where the application works fine in development build but breaks in production build. Upon loading the application, the following error is displayed. Uncaught TypeError: Cannot read p ...

Challenge when providing particular strings in Typescript

Something seems to be wrong with the str variable on line number 15. I would have expected the Typescript compiler to understand that str will only ever have the values 'foo' or 'bar' import { useEffect } from 'react' type Ty ...

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...

Is it possible to obtain Literal types for object keys dynamically in typescript?

I am looking to extract the type of object keys. Below is a generic function for objects with keys as strings: type GenericInput = { [key:string]: {value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, err ...

Tips for defining a function across a Angular project

I have the following configuration set up in an Angular5 project using Angular-cli 1.5 within typings.d.ts declare interface String { toSentenceCase(): string; } declare function _debug(o, message?, type?): void; inside app/core/common.ts String.pro ...

Aurelia CLI encounters difficulty importing chart.js when using TypeScript

Currently, I am utilizing typescript with aurelia/aurelia-cli. After npm installing chart.js, I proceeded to add it to my aurelia.json file like so: "dependencies": [ ... { "name": "chartjs", "path": "../node_modules/chart.js/d ...

"I am facing issues with Nodejs $lookup as it is not producing the

I am looking to merge two document collections. The first collection, "prefix," contains an array of category IDs under the categoryId key, while the second collection, "categories," holds objects with a unique _id field. Here is my sample database structu ...