简体   繁体   English

是否可以基于某些 model 创建动态 Typescript 类型?

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

Consider I have an Address interface model:考虑我有一个Address接口 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:随着 Angular 14 发布,我想创建一个基于AddressModel的类型化表单组,其中键是表单控件的名称,值是表单控件本身,带有键的透视值,因此结果 model 将是:

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?我知道这可以手动创建 model 但也许 Typescript 具有自动化此过程的功能?

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 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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