【问题标题】:vue ref property not able to infer type correctlyvue ref 属性无法正确推断类型
【发布时间】:2022-11-15 13:26:12
【问题描述】:

想向可组合方法添加一个额外的属性,但它抛出错误property 'isActive' does not exist on type '{ id: string; text: string; }'

这是代码

import { ref, type Ref } from 'vue';

type ActiveItemType = {
  text: string;
  isActive?: boolean;
};

export const useActiveItems = <T extends ActiveItemType>(data: T[]) => {
  let active = '';

  function activeMapper(d: T) {
    return {
      ...d,
      isActive: d.text === active,
    };
  }
  const itemsData = data.map(activeMapper);

  const items = ref(itemsData) as Ref<T[]>;

  function onSetActive(text: string) {
    active = text;
    items.value = items.value.map(activeMapper);
  }

  // initial set first one
  if (items.value[0]) {
    items.value[0].isActive = true;
  }

  return {
    items,
    onSetActive,
  };
};

const { items } = useActiveItems([
  {
    id: '1',
    text: 't1'
  },
  {
    id: '2',
    text: 't2'
  },
]);

if (items.value[0]) {
  items.value[0].isActive; // ERROR
}

ts-playground-link

使用 hit n trial 我发现,如果我像这样在我的方法中创建一个类型,它会起作用,但我不确定它是否是正确的方法?或者我们应该只在方法头中创建类型,即在 <> 中?

type U = T & ActiveItemType;
const items = ref(itemsData) as Ref<U[]>;

【问题讨论】:

    标签: typescript vue.js vuejs3 vue-composition-api


    【解决方案1】:

    基于此issue comment

    当使用泛型 refreactive 时,如果您确定该类型没有任何嵌套引用,则需要强制转换为 as Ref&lt;T&gt;as reactive&lt;T&gt;,因为 ref 和 reactive 会自动解开嵌套引用

       import {ref, Ref} from 'vue';
      // ... 
       const items = ref(itemsData) as Ref<T[]>;
    

    【讨论】:

    • 然后 items[0].isActive 不可用
    • 尝试添加属性 isActive T extends { icon: string; text: string, isActive?: boolean }
    • 问题已更新...我仍然无法弄清楚,因为 `Ref<T & ActiveItemType[]>;` 不是有效的语法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2011-10-16
    • 2021-06-11
    • 2020-08-16
    相关资源
    最近更新 更多