Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning possible null even when validate it

I have the following code:

export function validaterUserContributors(
  propList: FormPropList<IdentityUserDto>
) {
  const firstNameNode = propList.dropByValue(
    'AbpIdentity::DisplayName:Name',
    (prop, displayName) => prop.displayName === displayName
  );

  const emailControlValue = firstNameNode?.value;

  if (emailControlValue) {
    const emailControl = new FormControl(
      emailControlValue,
      Validators.required
    );

    propList.add(emailControl.value);

}

As you can see, I created a new form control of the first one I dropped, and I added a validator., so I want to add it in the last line propList.add(emailControl.value);

But this is throwing me the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Argument of type ‘FormProp | null’ is not assignable
to parameter of type ‘FormProp’. Type ‘null’ is not
assignable to type ‘FormProp’

I don’t know why it has possible null if I use an if statement to control that if (emailControlValue) {}

Any ideas what am I doing wrong?

>Solution :

The issue seems to be with the way you’re using the optional chaining operator (?) when accessing the value property of firstNameNode

Even though you’re checking if emailControlValue is truthy before creating a new FormControl, TypeScript is still recognizing that firstNameNode could potentially be null or undefined due to the usage of ?

To fix this issue, you can either remove the ? and use a non-null assertion operator (!) like this:

const emailControlValue = firstNameNode!.value;

Or, you can use a nullish coalescing operator (??) to provide a default value in case firstNameNode is null or undefined:

const emailControlValue = firstNameNode?.value ?? '';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading