You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15中TypeScript错误TS2345的修复咨询

Angular 15 + TypeScript 错误TS2345修复方案

问题描述

在Angular 15.0.0版本中编写代码时,遇到TypeScript错误TS2345:Argument of type 'number' is not assignable to parameter of type 'never',错误出现在is-disabled.component.ts第26行的map操作符中,尝试手动声明类型后仍未解决。

错误原因

核心问题是未给FormControl指定泛型类型,导致TypeScript无法推断denyListedUsers和selectedUserId的值类型:

  • denyListedUsers默认被推断为FormControl<never[]>,其值类型是never[]
  • selectedUserId被推断为FormControl<unknown>,经过map转换后得到number类型
  • 当调用denyList.includes(selected)时,never[]类型的数组无法接受number类型的参数,触发类型错误

修复方案

给所有FormControl添加明确的泛型类型,同时优化空值处理逻辑:

修复后的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},
  ];

  // 明确指定FormControl的泛型类型,匹配实际值类型
  denyListedUsers = new FormControl<number[]>([]);
  selectedUserId = new FormControl<number | null>(null);
  allowDenyListedUsers = new FormControl<boolean>(false);

  isDisabled$ = combineLatest([
    this.allowDenyListedUsers.valueChanges.pipe(startWith(false)),
    this.denyListedUsers.valueChanges.pipe(startWith([])),
    this.selectedUserId.valueChanges.pipe(
      startWith(null),
      // 处理未选择用户的情况,返回一个不存在的ID避免类型问题
      map(id => id ? +id : -1)
    ),
  ]).pipe(
    map(([allowDenyListed, denyList, selected]) => {
      // 逻辑优化:未选择用户时按钮也禁用,可根据需求调整
      return !allowDenyListed && selected !== -1 && denyList.includes(selected);
    }),
  )
}

关键修复点

  1. 泛型类型声明:

    • denyListedUsers指定为FormControl<number[]>,明确其值是用户ID数组
    • selectedUserId指定为FormControl<number | null>,匹配“选择用户/未选择”的状态
    • allowDenyListedUsers指定为FormControl<boolean>,让类型声明更完整
  2. 空值处理优化:
    将原来的map(id => +id!)改为map(id => id ? +id : -1),避免强制非空断言(!)带来的潜在运行时风险,同时确保selected始终为number类型,与denyList的number[]类型完全兼容。

内容的提问来源于stack exchange,提问作者albertkao9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:45:37