Search code examples
angulartypescriptrxjsangular15

Typescript error TS2345: Argument of type 'number' is not assignable to parameter of type 'never'


The following Angular Typescript code has an error:

src/app/is-disabled/is-disabled.component.ts:26:89 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'never'.

26 ([allowDenyListed, denyList, selected]) => !allowDenyListed && denyList!.includes(selected),

I am learning Angular, Typescript and Rxjs. I think I need to declare the proper type for line 26. I tried but still, get the same error. How to fix it?

is-disabled.component.html:

<select [formControl]="selectedUserId">
    <option>Select a User</option>
    <option *ngFor="let user of users" [value]="user.id">{{ user.name }}</option>
</select>
<select [formControl]="denyListedUsers" multiple>
    <option *ngFor="let user of users" [value]="user.id">{{ user.name }}</option>
</select>
Allow deny listed users <input type="checkbox" [formControl]="allowDenyListedUsers" />
<button [disabled]="isDisabled$ | async">Submit</button>

is-disabled.component.ts:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { combineLatest, map, startWith } from 'rxjs';

@Component({
  selector: 'app-is-disabled',
  templateUrl: './is-disabled.component.html',
  styleUrls: ['./is-disabled.component.css']
})
export class IsDisabledComponent {
  users = [
    {name: 'Peter', id: 1},
    {name: 'Paul', id: 2},
    {name: 'Mary', id: 3},
  ];

  denyListedUsers = new FormControl([]);
  selectedUserId = new FormControl(null);
  allowDenyListedUsers = new FormControl(false);
  isDisabled$ = combineLatest([
    this.allowDenyListedUsers.valueChanges.pipe(startWith(false)),
    this.denyListedUsers.valueChanges.pipe(startWith([])),
    this.selectedUserId.valueChanges.pipe(startWith(null), map(id => +id!)),
  ]).pipe(
    map(
      ([allowDenyListed, denyList, selected]) => !allowDenyListed && denyList!.includes(selected),
    ),
  )
}

The Angular version is 15.0.0.


Solution

    1. Use strong-typed FormControl.
    denyListedUsers = new FormControl<number[]>([] as number[]);
    
    1. Next, you have to define empty array [] as number[] type.
    this.denyListedUsers.valueChanges.pipe(startWith([] as number[]))
    

    Or without startWith rxjs operator could be worked as well.

    this.denyListedUsers.valueChanges.pipe()
    

    Demo @ StackBlitz