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:

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 ?? '';

Leave a Reply