Error Ts2742: the Inferred Type of 'Username' Cannot Be Named Without a Reference to '. .. /Node_Modules/@Angular/Forms/Forms'

I'm getting this error in my application:

forgot-password.component.ts(44,7): error TS2742: The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'. This is likely not portable. A type annotation is necessary.

import { Component, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { User } from '../../models';
import { ValidateUsername } from '../../validators/userid-validator';

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent {
  forgotPasswordForm: FormGroup;
  @Output() resetPassword: EventEmitter<any> = new EventEmitter<any>();
  @Output() onSubmit: EventEmitter<User> = new EventEmitter<User>();
  constructor(private formBuilder: FormBuilder, private router: Router) {
    this.forgotPasswordForm = this.formBuilder.group({
      username: ['', [Validators.required, ValidateUsername]]
    });
  }
  get username() { return this.forgotPasswordForm.get('username'); }
  passwordToken(event$) {
    this.onSubmit.emit(event$.value);
  }
}

The error occurs at this line:

 get username() { return this.forgotPasswordForm.get('username'); }
2

6 Answers

remove

"declaration": true,

in your tsconfig.json

3

You need to be explicit on the return type of the property.

get username(): AbstractControl { return this.forgotPasswordForm.get('username'); }

forgotPasswordForm is a FormGroup and its get() method returns an AbstractControl with the following subclasses

Subclasses

  • FormArray
  • FormControl
  • FormGroup

When it says

This is likely not portable. A type annotation is necessary.

Sometimes you need to check your tsconfig.json and see if is there anything wrong with "baseUrl", "paths" and linked packages too.

But in this case, TS is accusing that you have not typed it since it is in your ts config, so either you can type it as "any", create an interface for it or type as necessarily, in this case, as string.

1

In my case, I found the following fixes:

#1 Export the reference as type

// Following is not working:
// export type { ObjectId as _ObjectId } from 'mongodb/node_modules/bson';

import type { ObjectId } from 'mongodb/node_modules/bson';
export type _ObjectId = ObjectId;
  • I import the reference as type.
  • I use _ObjectId as name, in order to avoid IDE autocompletion with it.
Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.