【问题标题】:Vue 2 / Typescript, how to cast a prop inline?Vue 2 / Typescript,如何内联投射道具?
【发布时间】:2022-01-09 01:59:22
【问题描述】:

我有一个带有 Typescript 的 Vue 2 NuxtJS 项目设置,我想利用 Typescript 中的 unknown 关键字。

在我的组件中,我收到一个这样声明的道具

props: { 
  items: {
    type: Array as () => LabelValuePair[],
    required: true,
  },
},

LabelValuePair 在这里声明

interface LabelValuePair {
  label: string;
  value: unknown;
}

在我的模板中,我想使用这样的东西

<li v-for="item in items" :key="item.value as string">
  <span>
    {{ item.label }}: <strong>{{ item.value }}</strong>
  </span>
</li>

问题是,除了三元运算符,as Typescript 关键字不被 vue 编译器识别为有效语法。

是否有解决方案或解决方法至少可以避免做类似以下的愚蠢事情?

setup(props) {
  const castItems = props.items.map((item) => ({
    ...item,
    value: item.value as string,
  }));

  return { castItems };
},

【问题讨论】:

  • 脚本部分是什么样子的?
  • 如果应该是string,为什么输入为unknown?如果你不知道会发生什么?
  • @EstusFlask 如果我将其保持为未知,则会出现 linting 错误 - 类型 'unknown' 不可分配给类型 'string |号码 |符号 |不明确的'。类型“未知”不可分配给类型“符号”.ts(2322)。 runtime-dom.d.ts(1478, 3):预期类型来自属性“key”,该属性在此处声明为“ElementAttrs”类型。
  • @EstusFlask 我使用unknown,因为我可以将这种类型与对象作为值而不是字符串重用。
  • 那这是一个需要解决的问题,需要缩小类型。指定除字符串 | 之外的任何内容都是不正确的。号码 |符号 |未定义的键(和未定义的键)。

标签: typescript vue.js


【解决方案1】:

如果 LabelValuePair 应该被重用,并且应该在 prop 中具有 string 值,那么泛型类型就是这种情况:

interface LabelValuePair<T = unknown> {
  label: string;
  value: T;
}

和

  items: {
    type: Array as PropType<LabelValuePair<string>[]>,
    required: true,
  },

【讨论】:

  • 太棒了!这确实是泛型的一个很好的用例,但我完全忘记了它们!感谢您的建议
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 2021-06-27
  • 2021-06-04
  • 2019-11-10
  • 2021-10-25
  • 2018-12-10
  • 2018-01-27
相关资源
最近更新 更多