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

TypeScript报错:Property 'url' does not exist on type 'never' 求解

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

核心问题在于你给play状态初始化时只传了空数组[],TypeScript无法推断数组元素的类型,会默认把它判定为never[](表示这个数组永远不会有有效元素)。当你在handleMix里访问play[index].url时,TS认为数组元素是never类型,自然不存在url属性,因此报错。

修复步骤

  1. 给play状态明确指定类型
    给useState添加泛型,明确play是你定义的Mix类型的数组:

    const [play, setPlay] = useState<Mix[]>([])
    

    这样TS就知道play数组里的每个元素都符合Mix结构,访问url属性就不会再报错。

  2. 优化handleSubmit的写法(可选但推荐)
    你当前混用了await和.then(),统一用async/await能让代码更简洁易读:

    const handleSubmit = async () => {
      const response = await fetch(url, options);
      const data = await response.json();
      setPlay(data.data);
    }
    
  3. 简化map的类型标注(可选)
    既然已经给play指定了Mix[]类型,map遍历的元素类型会自动推断为Mix,可以去掉显式的:Mix标注:

    {play.map((mix, index) => (
      <div className='cursor-pointer gap-2' key={index} onClick={()=>handleMix(index)}>
        <p>{mix.name}</p>
      </div>
    ))}
    

核心修改后的代码片段

const Search = () => {
    const [search, setSearch] = useState<string>("")
    // 明确play的类型为Mix[]
    const [play, setPlay] = useState<Mix[]>([])
    const [mix, setMix] = useState<string>("")
    const url = `https://api.mixcloud.com/search/?q=${search}&type=cloudcast`
    
    // 优化后的请求逻辑
    const handleSubmit = async () => {
        const response = await fetch(url, options);
        const data = await response.json();
        setPlay(data.data);
    }

    const handleMix = (index:number) => {
        setMix(`https://app.mixcloud.com/oembed/?url=${play[index].url}`)
    }

    // 其余渲染代码不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:02:41