How to limit the value type of FormGroup in ts?
P粉566048790
P粉566048790 2023-09-09 16:19:03
0
1
434

I have a constant like this:

const defaultInfo: FormGroup = this.fb.group({
  id: 1,
  name: qian,
  amount: 123,
})

And I want to limit the types inside FormGroup, so I write like this:

interface InfoInterface {
  id: number,
  name: string,
  amount: number,
}


interface InfoFormGroup extends FormGroup {
  value: InfoInterface
}

const defaultInfo: InfoFormGroup = this.fb.group({
  id: 1,
  name: qian,
  amount: 123,
})

Apparently it doesn't work because no matter what I change the properties of the Info Interface to, there are no errors, why? How to limit the value type of FormGroup in ts

Restrict the value type of FormGroup in ts

P粉566048790
P粉566048790

reply all(1)
P粉378264633

I think it should help you: https://angular.io/guide/typed-forms

Basically you need to make the interface have form controls instead of normal types:

interface InfoInterface {
      id: FormControl<number>,
      name: FormControl<string>,
      amount: FormControl<number>
  }
    
  const info = new FormGroup<InfoInterface>({
      id: new FormControl(0),
      name: new FormControl(''),
      amount: new FormControl(0)
  });

Please keep in mind that it was introduced in Angular 14, so it will not work in previous versions

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template