Is it possible to have a type check in type definition in the TypeScript

Viewed 43

I have a class for returning reactive forms as forms with available controls listed in IntelliSense. That works fine for FormControls but what I would like to achieve is to have FormGroups that are part of queried parent FormGroup to be returned as TypedFormGroup<T[key]>, hope that makes sense, is there any way I can have some type of assertion like controls!: { [key in keyof T]: (AbstractControl & T[key] is string) | TypedFormGroup<T[key]>} ?

export class TypedFormGroup<T> extends FormGroup {
  controls!: { [key in keyof T]: AbstractControl }

  constructor(controls: { [key in keyof T]: AbstractControl }) {
    super(controls);
  }
}
1 Answers

Found solution to my problem

export interface TypedFormGroup<T> extends FormGroup {
  controls: { [key in keyof T]: T[key] extends (string | number | boolean) ? AbstractControl : TypedFormGroup<T[key]> }
}
Related