I want to be able to define my own methods for a custom angular FormGroup. So I created a class that extends the default angular formgroup, and I want it to be of the same type as IUnitForm
initForm(): FormGroup<IForm> {
return this.formBuilder.group<IForm>({
weight: new UnitFormGroup<MassUnit>({
unit: new FormControl<MassUnit>(MassUnit.gram),
unitValue: new FormControl<number>(11)
} as IUnitForm<MassUnit>)
});
}
export interface IForm {
weight: UnitFormGroup<UnitType>;
}
export class UnitFormGroup<T extends UnitType> extends FormGroup implements IUnitForm<T> {
unit: FormControl<T>;
unitValue: FormControl<number>;
constructor(controls: IUnitForm<T>) {
super(controls);
this.unit = controls.unit;
this.unitValue = controls.unitValue;
}
addOne(): void {
const newValue = this.unitValue.value + 1;
console.log(newValue);
}
}
export type UnitType = MassUnit | LengthUnit | DistanceUnit | SpeedUnit | TemperatureUnit;
export enum MassUnit {
gram = 'gram',
grain = 'grain',
ounce = 'ounce'
}
export enum LengthUnit {
millimeter = 'millimeter',
inch = 'inch'
}
export enum DistanceUnit {
meter = 'meter',
yard = 'yard'
}
export enum SpeedUnit {
meterSecond = 'meterSecond',
feetSecond = 'feetSecond'
}
export enum TemperatureUnit {
celsius = 'celsius',
fahrenheit = 'fahrenheit'
}
export interface IUnitForm<T extends UnitType> {
unit: FormControl<T>;
unitValue: FormControl<number>;
}
On return this.formBuilder.group<IForm>
I get the error
Type 'FormGroup<{ weight: FormGroup<{ [key: string]: AbstractControl<any, any>; }>; }>' is not assignable to type 'FormGroup<IBulletForm>'.
Types of property 'controls' are incompatible.
Type '{ weight: FormGroup<{ [key: string]: AbstractControl<any, any>; }>; }' is not assignable to type 'IBulletForm'.ts(2322)
How can I fix this type mismatch?