I have a human
object.
interface Human {
ID: number;
gender: string;
hobbies?: string[];
}
I want to create a FormGroup with similar structure, how can I declare the typing for the FormGroup object?
interface HumanFormGroup {
ID: FormControl,
gender: FormControl,
hobbies?: FormArray
}
I am creating this FormGroup manually, but hopping that I can do something like:
const humanForm: ValueAny<Human>
Is it possible?
P/S: I asked this because there are Partial<T>
modifier available, but not sure if there are any "ValueAny" modifier?
答案 0 :(得分:3)
您可以使用mapped type和conditional type来实现。映射的类型将映射原始类型的属性,而条件类型将根据其是否为数组来转换属性的原始类型。
interface Human {
ID: number;
gender: string;
hobbies?: string[];
}
type ValueAny<T> = {
[P in keyof T] : T[P] extends any[] ? FormArray : FormControl
}
type HumanFormGroup = ValueAny<Human>
// Will be quivalent to
// {
// ID: FormControl,
// gender: FormControl,
// hobbies?: FormArray
// }
您可以进一步使映射规则复杂化,但是从您的问题出发,这些是我推断的要求。