Home > Blockchain >  Is it possible to create dynamic Typescript type based on some model?
Is it possible to create dynamic Typescript type based on some model?

Time:09-07

Consider I have an Address interface model:

interface AddressModel {
  street: string | null;
  streetNumber: string | null;
  postalCode: string | null;
  city: string | null;
  country: string | null;
  latitude: number | null;
  longitude: number | null;
}

As Angular 14 released, I would like to create a typed form group based on AddressModel, where the key would be name of the form control and the value is a form control itself with the perspective value of the key, so the result model would be:

interface AddressFormGroup {
  street: FormControl<string | null>;
  streetNumber: FormControl<string | null>;
  postalCode: FormControl<string | null>;
  city: FormControl<string | null>;
  country: FormControl<string | null>;
  latitude: FormControl<number | null>;
  longitude: FormControl<number | null>;
}

I know this can be done creating the model manually but maybe Typescript has features to automate this process?

CodePudding user response:

A simple mapped type will do this for you.

type ToFormControl<T> = {
    [K in keyof T]: FormControl<T[K]>
}
type AddressFormGroup = ToFormControl<AddressModel>

// type AddressFormGroup = {
//     street: FormControl<string | null>;
//     streetNumber: FormControl<string | null>;
//     postalCode: FormControl<string | null>;
//     city: FormControl<string | null>;
//     country: FormControl<...>;
//     latitude: FormControl<...>;
//     longitude: FormControl<...>;
// }

Playground

  • Related