Issue
I have a bunch of classes with a body
property, like so:
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 class types are then referenced in an object, where they can be picked up and referenced by a string:
const pages = {
'foo': Foo,
'bar': Bar
} as const
I then have a union type that references all of my classes:
type Pages = typeof pages[keyof typeof pages]
// typeof Foo | typeof Bar
How do I get an object that references all the types of the body
properties of each class in the pages
object? Something like:
// The values for `fooBody` and `barBody` are types here
{
'fooBody': {foo: string},
'barBody': {bar: string}
}
Solution
Storing the pages as an object of name to class (constructor) makes it really difficult, if you turn it to a type then it becomes much easier.
type pages = {
foo: Foo
bar: Bar
}
type AllBodies = {
[Property in keyof pages as `${Property}Body`]: pages[Property]['body']
}
const allBodies: AllBodies = {
fooBody: { foo: 'string' },
barBody: { bar: 'string' },
}
Answered By - plasma147
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.