Search code examples
angulartypescriptangular-reactive-forms

How to specify types on values returned from an Angular form?


In an Angular project, I have a form:

  constructor() {
   this.form = new FormGroup({
      description: new FormControl<string|undefined>({ value: undefined, disabled: false }),
      expectedStart: new FormControl<Date|undefined>({ value: undefined, disabled: false }),
      expectedEnd: new FormControl<Date|undefined>({ value: undefined, disabled: false }),
      priority: new FormControl<string|undefined>({ value: undefined, disabled: false })
    })
  }

I am destructuring the raw value returned from the form in my save function:

const {
  description,
  expectedStart,
  expectedEnd,
  priority,
} = this.form.getRawValue()

But all of those new variables are type any.

Is there a way to type them?


Solution

  • you can use something like this :

    const { name, age }: { name: string; age: number } = body.value
    

    The best way to approach this would be to create a type or interface for that data:

    interface Human {
      name: string
      age: number
    }
    
    const human: Human = body.value
    

    Regards,