TypeScript类型检查错误 error TS2339

错误产生

上一篇博客写了一个调用摄像头的 demo ,用了 vue3 + vite ,使用了 TypeScript ,代码大致如下:

<script setup lang="ts">
import {
    
     onMounted, ref } from 'vue';
import WelcomeItem from './WelcomeItem.vue'
import ToolingIcon from './icons/IconTooling.vue'
import axios from 'axios';
import {
    
     ACCESS_TOKEN } from '../config/constants';

const devices = ref([]);

const fetchDevices = async () => {
    
    
  try {
    
    
    const response = await axios.post(`https://open.ys7.com/api/lapp/device/list?accessToken=${
      
      ACCESS_TOKEN}&pageStart=0&pageSize=40`);

    if (response.status === 200) {
    
    
      devices.value = response.data.data;
      console.log(response.data)
    } else {
    
    
      console.error('Failed to fetch devices:', response.statusText);
    }
  } catch (error) {
    
    
    console.error('Error fetching devices:', error);
  }
};

onMounted(() => {
    
    
  fetchDevices();
});

</script>
<template>
    <WelcomeItem v-for="(device) in devices" :key="device.id">
    <template #icon>
      <ToolingIcon />
    </template>
    <template #heading>{
    
    {
    
     device.deviceName }}</template>  
    <a :href="'/player/?id=' + device.deviceSerial + '&template=pcRec'" target="_blank">回放</a>
    <a :href="'/player/?id=' + device.deviceSerial + '&template=pcLive'" target="_blank">直播</a>
  </WelcomeItem>
</template>

在开发环境运行是没有问题的,但如果使用,npm run build (配置为类型检查,即 run-p type-check \"build-only {@})时,出现如下错误:

transforming (397) node_modules\axios\lib\platform\browser\classes\URLSearchParams.jssrc/components/ThePlayList.vue:31:59 - error TS2339: Property 'id' does not exist on type 'never'.

31     <WelcomeItem v-for="(device) in devices" :key="device.id">
                                                             ~~

src/components/ThePlayList.vue:35:34 - error TS2339: Property 'deviceName' does not exist on type 'never'.

35     <template #heading>{
    
    { device.deviceName }}</template>
                                    ~~~~~~~~~~

src/components/ThePlayList.vue:36:39 - error TS2339: Property 'deviceSerial' does not exist on type 'never'.

36     <a :href="'/player/?id=' + device.deviceSerial + '&template=pcRec'" target="_blank">回放</a>
                                         ~~~~~~~~~~~~

src/components/ThePlayList.vue:37:39 - error TS2339: Property 'deviceSerial' does not exist on type 'never'.

37     <a :href="'/player/?id=' + device.deviceSerial + '&template=pcLive'" target="_blank">直播</a>
                                         ~~~~~~~~~~~~


Found 4 errors.

ERROR: "type-check" exited with 2.

解决办法

1. 不做类型检查

这是简单粗暴的办法,也是鸵鸟策略,不检查直接生成不就行了。

npm run build-only

也就是 vite build,能正确生成。
鸵鸟策略

2. 按照出错的问题修改

忽略掉总是不好,那么,可以修改出错的地方,这里主要是 AJAX 返回的 devices 的类型问题,因为是 JSON 返回,可以考虑为 any 类型,于是进行了局部的修改:

const devices = ref<any>([]);

再次执行含 type-check 的生成命令

npm run build

错误提示消失。

猜你喜欢

转载自blog.csdn.net/Humbunklung/article/details/141682230