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

Angular 2 code test coverage

Looking to calculate the code coverage of my Angular 2 code. Wondering if there are any plugins available for VS Code or WebStorm that can assist with this. My unit testing is done using Jasmine and Karma. ...

In Typescript 2.2, when using Express, the request and response objects are implicitly

I'm facing some challenges when it comes to incorporating types into my node/express project. Currently, I am using TypeScript 2.2 and express 4.x with the following npm installation for types: npm install --save-dev @types/express import * as expr ...

Challenges arise when incorporating interfaces within a class structure

I created two interfaces outside of a class and then proceeded to implement them. However, when I tried to assign them to private properties of the class, something went wrong and I'm unable to pinpoint the issue. Can anyone offer assistance with thi ...

Exploring the functionality of typeahead with server-side data integration

I am utilizing ng-select with Angular 7 and creating the following component: export class PostComponent { selectedCategoryID: number; allCategories$: Observable<CategoryModel[]>; constructor(private catService: CategoryService) { } ngOn ...

Typescript: Issue encountered with Record type causing Type Error

When utilizing handler functions within an object, the Record type is used in the following code snippet: interface User { id: string; avatar: string; email: string; name: string; role?: string; [key: string]: any; } interface Stat ...

Trigger a function upon a user's departure from a page or route in Angular 2

Is there a way to trigger a function only when the current route changes away from a specific component, such as when navigating away from "..../user/user-details"? I want this method to execute regardless of whether the route is changed through user inter ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

Creating an array of objects using Constructors in Typescript

Utilizing TypeScript for coding in Angular2, I am dealing with this object: export class Vehicle{ name: String; door: { position: String; id: Number; }; } To initialize the object, I have followed these steps: constructor() { ...

Having trouble with Typescript in React and Firestore? Wondering why you are receiving the error message "Variable 'l' implicitly has type 'any[]' in some locations where its type cannot be determined.ts"?

For my To Do List project, I am utilizing Next.js/React with Firebase as the backend. The task items consist of name, time required for task completion, and due date fields. My goal is to retrieve the items from the Firebase collection and set them in setD ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue. I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic. ESLint: Unexpected any. Specif ...

React throwing a typescript error while attempting to update state based on the previous state

Hello there! I'm fairly new to working with TypeScript and I've encountered an issue with a piece of state in a child component. I'm trying to modify it based on the previous value, but every time I call the setState function, I get a type e ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

Issue with ngx-bootstrap custom typeahead feature malfunctioning

I'm facing an issue while trying to develop a customized typeahead feature that is supposed to search my API every time the user inputs something, but it's not functioning as expected. The autocomplete() function isn't even getting accessed. ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...

The search for 'partition' in 'rxjs' did not yield any results

Recently, I attempted to incorporate ng-http-loader into my Angular project. After successfully installing the ng-http-loader package, I encountered an error during compilation. The specific error message displayed was: export 'partition' was ...

Exploring the power of nested components within Angular 2

I am encountering an issue with a module that contains several components, where Angular is unable to locate the component when using the directive syntax in the template. The error message I receive states: 'test-cell-map' is not a known elemen ...

Altering the inner HTML content of a div using the ID within an Angular component function

Attempting to change the inner HTML content of a div using its id with another div in an Angular component method. Successfully calling the populateEndpointHomeContent() method and retrieving the content, but encountering issues with subsequent content. Th ...

I rely on the angular-responsive-carousel library for my project, but unfortunately, I am unable to customize the arrow and dots

When it comes to CSS, I utilize ng deep style in Angular 10 to make changes for browser CSS. However, I am facing an issue where the problem is not being resolved by my CSS code. Here is a snippet of my code: > ::ngdeep .carousel-arrow { > b ...