vue3.0 typescript 类型问题

  1. vue3.0 ref 如下片断:GlobalSearchInfo.value.searchInfo = "" 这句类型怎么定义?
<child ref="GlobalSearchInfo"> </child>
const GlobalSearchInfo = ref<null | HTMLElement>(null);
GlobalSearchInfo.value.searchInfo = "";

提示:

Object is possibly 'null'.
Property 'searchInfo' does not exist on type 'HTMLElement'
  1. state.menuData = menuData.concat(checkData)这行标红提示如下:

     const state = reactive<DataProps>({
       menuData: [{ id: "", systemNm: "", count: 0, checked: false }],
       topicData: [],
       totalNum: 0,
      })
    
     const topicData = [
       { id: "001", subjAreaNm: "不限", count: 0, checked: true },
     ];
    
     const menuData = [
       { id: "001", systemNm: "全部", count: 0, checked: true },
     ];
     function addChecked(data) {
       for (let i = 0; i < data.length; i++) {
         data[i].checked = false;
       }
       return data;
     }
       // 请求返回的数据添加checked
       const checkData = addChecked(res.data);
       state.menuData = menuData.concat(checkData);

    提示:

Type '{ id: string; subjAreaNm: string; count: number; checked: boolean; }[]' is not assignable to type '[]'.
  Target allows only 0 element(s) but source may have more.
  1. totalNum赋值:
    state.totalNum = res.total;

提示:

Property 'total' does not exist on type 'AxiosResponse<any, any>'
  1. state.topicDatachecked需要类型:
    const onRestoreTopicSelect = () => {
      for (let i = 0; i < state.topicData.length; i++) {
        if (i === 0) {
          state.topicData[i].checked = true;
        } else {
          state.topicData[i].checked = false;
        }
      }
    };

提示:

Object is possibly 'undefined'
Property 'checked' does not exist on type 'never'.
阅读 8.2k
1 个回答
  1. 提示给出的信息是GlobalSearchInfo.value可能是null,这样你GlobalSearchInfo.value.searchInfo就会报错,第二个提示是说HTMLElement这种类型上没有searchInfo这个属性
    如果你是想修改组件里的data或者调用里面的方法 可以这样

    const GlobalSearchInfo = ref<InstanceType<typeof child>>()
  2. 应该是你 addChecked 的返回值推断不出来是什么类型,你补充下类型试试

    function addChecked(data: Array<MenuDataType>) {
    for (let i = 0; i < data.length; i++) {
      data[i].checked = false;
    }
    return data;
    }
  3. 提供的代码太少了,AxiosResponse类型给一下,res是什么样,提示的消息是说AxiosResponse<any, any>不能确定有没有total属性
  4. 提示基本也是说你类型没定义好, topicDatatopicData[i]有可能是undefined,提示二 never 说明肯定是 topicData[i] 可能是个never,而never上肯定不包含checked这个属性

    interface CommonDataType {
      id: string
      count: number
      checked: boolean
    }
    
    type MenuDataType = CommonDataType & {
      systemNm: string
    }
    
    type TopicDataType = CommonDataType & {
      subjAreaNm: string
    }
    
    interface DataProps {
      menuData: Array<MenuDataType>
      topicData: Array<TopicDataType>
      totalNum: number
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题