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

从React迁移到TypeScript:'value不存在于never类型'错误排查

解决TypeScript中"Property 'value' does not exist on type 'never'"错误

这个错误的核心原因是TypeScript无法推断selectedStates和selectedBreeds的数组元素类型,默认将它们判定为never[]类型,自然无法访问.value属性。以下是具体解决步骤:

1. 定义选项类型

先为两个数组的元素明确类型,根据业务场景补充属性(比如常见的label):

// 州选项类型
type StateOption = {
  value: string; // 若实际值是数字则改为number
  label?: string; // 可选,根据组件实际结构添加
};

// 犬种选项类型
type BreedOption = {
  value: string;
  label?: string;
};

2. 为状态变量指定类型

如果selectedStates和selectedBreeds是用useState声明的,需要在声明时指定泛型类型,避免TS默认推断为never[]:

import { useState, useEffect } from 'react';

const [selectedStates, setSelectedStates] = useState<StateOption[]>([]);
const [selectedBreeds, setSelectedBreeds] = useState<BreedOption[]>([]);

3. 修复useEffect中的cities类型

直接给cities指定string[]类型,去掉临时的@ts-expect-error注释:

useEffect(() => {
    const cities: string[] = [];
    selectedStates.forEach((state) =>
      cities.push(...getCityByState(state.value).map((city) => city.name))
    );
    setCities(cities);
  }, [selectedStates]);

4. 确认getSearchQuery的类型兼容

修正selectedBreeds类型后,breed.value的访问会被TS认可,还可以给函数返回值加上类型注解:

const getSearchQuery = (zipCodes: string[]): string => {
    let query = Default_Search + `sort=breed:${selectedSort.value}&`;
    query += selectedBreeds
      .map((breed) => `dogBreeds=${breed.value}&`)
      .join("");
    query += zipCodes.map((zipcode) => `zipCodes=${zipcode}&`).join("");
    return query + `ageMin=${minAge.value}&ageMax=${maxAge.value}&`;
  };

补充说明

如果selectedSort、minAge、maxAge也出现类似类型问题,照搬上述逻辑即可:先定义对应选项类型,再为状态变量指定泛型类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:05:22