Encountered Typescript issue when utilizing typed forms in Angular

Below is the interface I am working with:

export interface ILoginDto {
  email: string;
  password: string;
}

Here is a snippet of the relevant code from the component:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class LoginComponent {

  form = this.getLoginForm();

  constructor(private readonly fb: FormBuilder) {
  }

  private getLoginForm(): FormGroup<ILoginDto> {
    return this.fb.nonNullable.group({
      email: ['', [Validators.email, Validators.required]],
      password: ['', [Validators.required]],
    });
  }
}

I encountered an error in TypeScript:

error TS2344: Type 'ILoginDto' does not satisfy the constraint '{ email: AbstractControl<any, any>; password: AbstractControl<any, any>; }'.
  Types of property 'email' are incompatible.
    Type 'string' is not assignable to type 'AbstractControl<any, any>'.

18   private getLoginForm(): FormGroup<ILoginDto> {
                                       ~~~~~~~~~

Additionally, I received the following error:

error TS2322: Type 'FormGroup<{ email: FormControl<string>; password: FormControl<string>; }>' is not assignable to type 'FormGroup<ILoginDto>'.
  Types of property 'controls' are incompatible.
    Type '{ email: FormControl<string>; password: FormControl<string>; }' is not assignable to type 'ILoginDto'.

19     return this.fb.nonNullable.group({
       ~~~~~~

Despite the documentation's guidance on simple interfaces, these errors occurred without explicit control type declarations.

For further exploration of the issue, try out the problem on the TypeScript Playground.

Answer №1

It seems like the type provided is incorrect because the form consists of form controls.

export interface ILoginForm {
  email: FormControl<string>;
  password: FormControl<string>;
}
You can retrieve the login form using this method:
private getLoginForm(): FormGroup<ILoginForm>

To maintain ILoginDto, you can use a mapped type:

type AsFormGroup<T> = FormGroup<{
 [K as keyof T]: FormControl<T[K]>
}>

type ILoginForm = AsFormGroup<ILoginDto>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Can you give me some insights about what an Action Creator is?

function createRefDoneAction(widgetsArray: widget[]): WidgetAction { return { type: actionTypes.REFRESH_WIDGET_DONE, widgets: widgetsArray }; } Could you please clarify the necessity of having two sets of parameters (e.g. 'wid ...

Issue with TypeScript retrieving value from an array

Within my component.ts class, I have defined an interface called Country: export interface Country{ id: String; name: String; checked: false; } const country: Country[] = [ { id: 'India', name: 'India', checked: false}, { ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

Creating a unique user interface for VSCode extension

Recently, I've delved into the world of developing extensions for Visual Studio. Unfortunately, my expertise in TypeScript and Visual Studio Code is quite limited. My goal is to create an extension that mirrors the functionality of activate-power-mod ...

Updating the Angular2 function in the main app component causes the current component to be reset

I developed an application that has the following structure: app.component.ts import { Component } from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import { NgClass } from &apos ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

How to set a new default environment in Angular CLI for running ng serve

Is there a way to make Angular CLI use a different environment file instead of the default dev when running ng serve? Update I should have clarified my question better. I am aware that we can specify the environment file using the --env switch, but I am ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

Struggling to execute a simple hello_world.ts script following a recent TypeScript installation on WSL

I've recently ventured into the realm of Typescript and decided to kick things off by following the official 5-minute tutorial available at: https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html npm install -g typescript However, ...

Utilize ngModel to access input files in the array

Within my form, there is a file upload input: <input type="file" [(ngModel)]="item.image" name="image" #image> Can I retrieve #image.files[0] using the ngModel item.image directly (without creating a reference)? If not, what exactly does ngModel s ...

The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value app ...

The functionality of NgbModal in ng-bootstrap is experiencing issues and becoming unresponsive in ng-bootstrap version 15 and Angular version 16

Currently, I am in the process of upgrading my Angular app from version 15 to version 16. Following the documentation, I have updated the @ng-bootstrap/ng-bootstrap package to version 15. However, after this update, I am facing issues with the NgbModals no ...

Efficiently Updating Property Values in Objects Using TypeScript and Loops

I have been looking into how to iterate or loop through a code snippet, and while I managed to do that, I am facing an issue where I cannot change the value of a property. Here is the snippet of code: export interface BaseOnTotalPaidFields { groupName ...

Modify the attributes of a CSS class according to the chosen theme (selected within the user interface) in Angular 8

I have a custom-built application with Angular 8 where users can switch between two unique themes in the user interface. I have a specific div class that I want to change the background-color for each theme, but unfortunately I am having difficulty achievi ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...