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

Optimizing your data layer in Angular2: A Guide to Best Practices

As a newcomer to Angular2, I am diving into hands-on learning. My current project involves building multiple views with parent components, child components, and database services. After successfully creating one view, I am now gearing up to implement other ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

Having trouble with Vue i18n and TypeScript: "The '$t' property is not recognized on the 'VueConstructor' type." Any suggestions on how to resolve this issue?

Within my project, some common functions are stored in separate .ts files. Is there a way to incorporate i18n in these cases? // for i18n import Vue from 'vue' declare module 'vue/types/vue' { interface VueConstructor { $t: an ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Merging Type-GraphQL and Typegoose through a Variety of Decorators

Using a combination of Type-GraphQl and Typegoose, I aim to streamline my data definitions by consolidating them into one source for both GraphQL schemas and Mongoose queries. Is it feasible to merge the two libraries in a way that allows me to describe bo ...

Cannot assign an array of Typescript type Never[] to an array of objects

Creating an object array can sometimes lead to errors, let's take a look at an example: objectExample[a].push({ id: john, detail: true }); objectExample[a].push({ id: james, detail: false}); const objectExample = { a = [ { id: john, detail: true} ...

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

show the stored value inside the useRef variable

One of my challenges involves a variable const prediction = useRef<any>(null); A button triggers a function that updates the variable's value: function showResult() { classifier.current.classify(capture, (result) => { ...

Handling Click and Mouse Events with React [react-sortable-hoc, material-ui, react-virtualized]

I have come across an interesting example that I would like to share with you. Check out this live working example on Stackblitz When the delete button on the red bin icon is pressed, the onClick event handler does not get triggered (sorting happens inst ...

Nesting objects within arrays using Typescript Generics

Hello, I am currently attempting to assign the correct type to an object with nested values. Here is a link to the code in the sandbox: https://codesandbox.io/s/0tftsf interface Product { name: string, id: number productList?:ProductItem[] } interf ...

I'm encountering a ModuleNotFoundError that says: "Module not found: Error: Can't resolve". What could be causing this

I have encountered an issue while trying to create a blog post page on my NextJS website. The page displays correctly on my local machine, but when I deploy it to production, I am facing the following error and I am unsure of how to resolve it: Here is the ...

How can I access a TypeScript variable from a global var set in a .cshtml file?

I have defined several variables in my .cshtml file to be used in my angular services: <script> var _APIURL = '@(Url.Content("~/Admin/api/"))'; var _AREAURL = '@(Url.Content("~/Admin/"))'; var _APPURL = &a ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...