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

Vue+TypeScript中fetch报错:Ref<string>无法赋值给RequestInfo

解决Vue+TypeScript中fetch请求的类型错误

错误原因

你遇到的TS2345错误是因为keysUrl是Vue的响应式Ref对象,而fetch的第一个参数要求是RequestInfo类型(即原始字符串或Request实例)。Ref对象是一个包含.value属性的包装对象,本身并不具备Request类型的相关属性,因此类型不匹配。

解决方法

1. 直接访问Ref的原始值

在调用fetch时,通过.value获取Ref内部的字符串值:

async onSubmit() {
  const res = await fetch(keysUrl.value); // 加上.value访问原始字符串
  const keys = (await res.json())?.keys;

  console.log('submit', type, keysUrl.value, issuer, audience, keys);
}

2. 正确的类型标注

确保keysUrl的类型被正确定义:

  • 如果是组件内部的响应式变量:
    import { ref } from 'vue';
    
    // 明确标注为Ref<string>
    const keysUrl = ref<string>('https://your-api-url/keys');
    
  • 如果是从Props传入的:
    interface Props {
      keysUrl: string; // 先在Props接口中定义字符串类型
    }
    
    const props = defineProps<Props>();
    // 若需要响应式,用toRef转换
    const keysUrl = toRef(props, 'keysUrl');
    

3. 优化响应数据类型(可选)

为了避免res.json()返回any类型,可以自定义响应数据的接口:

interface KeyResponse {
  keys?: Array<{
    // 根据你的API返回结构定义具体字段
    kid: string;
    alg: string;
  }>;
}

async onSubmit() {
  const res = await fetch(keysUrl.value);
  const data = await res.json() as KeyResponse;
  const keys = data.keys;

  console.log('submit', type, keysUrl.value, issuer, audience, keys);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:35:18