简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM