Consider the setup provided:
enum FormGroups {
customer = 'customer',
address = 'address',
}
interface Customer {
'firstName': string;
}
interface Address {
'street': string;
}
interface SomeFormEvent {
valid: boolean;
forms: {
[FormGroups.customer]: {
values: Customer,
},
[FormGroups.address]: {
values: Address,
}
}
}
Here is what I intend to use:
type Forms = Customer | Address
This, however, is a static approach. If a new form is added in SomeFormEvent in the future like so:
interface SomeFormEvent {
valid: boolean;
forms: {
[FormGroups.customer]: {
values: Customer,
},
[FormGroups.address]: {
values: Address,
},
// a form is added here:
[FormGroups.preferences]: {
values: Preferences,
},
}
}
I would need to manually update the 'Forms' type as follows:
// manually have to add 'Preferences'
type Forms = Customer | Address | Preferences
Is there a more dynamic way to create the Forms type?
I've attempted the following:
enum FormGroups {
customer = 'customer',
address = 'address',
}
interface Customer {
'firstName': string;
}
interface Address {
'street': string;
}
interface SomeFormEvent {
valid: boolean;
forms: {
[FormGroups.customer]: {
values: Customer,
},
[FormGroups.address]: {
values: Address,
},
}
}
type Forms = { [K in keyof SomeFormEvent['forms']]: SomeFormEvent['forms'][K]['values'] }
function foo(): Forms {
return {
// error: Type '{ firstName: string; street: string; }' is
// not assignable to type 'Forms'. Object literal may only
// specify known properties, and 'firstName' does not exist
// in type 'Forms'.
firstName: 'sdfdsf',
street: 'sdffds'
}
}
However, this approach does not work.