我是 Vue 的新手,甚至是 TypeScript 的新手。我研究了两者的文档,并用它们构建了小型项目。然而,事实证明,使用 Vue 和 TS 进行组合具有挑战性。
按照 Net Ninja 教程,我想让 3 个按钮重新组织列表中某些作业的顺序。但是,即使我复制了他的代码,TS 还是在 IDE 中给了我错误。下游(可能是 ide 中显示的错误的下游问题)有一堆代码没有到达。我来给你展示。
<script lang="ts">
import { computed, defineComponent, PropType } from "vue";
import Job from "../types/Job";
import OrderTerm from "../types/OrderTerm";
export default defineComponent({
props: {
jobs: {
required: true,
type: Array as PropType<Job[]>,
},
order: {
required: true,
type: String as PropType<OrderTerm>,
},
},
setup(props) {
console.log("ce code est allerant", props, props.jobs);
const aaa = props;
const x = computed(() => {
console.log(
"this code was not reached; restated, it does not print, idk why"
);
return [...props.jobs].sort((a: Job, b: Job) => {
return a[props.order] > b[props.order] ? 1 : -1;
});
});
// console.log("fobar");
return { x };
},
});
</script>
我在 IDE 中收到此错误:
ype 'unknown' must have a '[Symbol.iterator]()' method that returns an iterator.Vetur(2488)
(parameter) props: Readonly<LooseRequired<Readonly<{
jobs: unknown;
order: unknown;
} & {}>>>
&
Type 'unknown' cannot be used as an index type.Vetur(2538)
(parameter) props: Readonly<LooseRequired<Readonly<{
jobs: unknown;
order: unknown;
} & {}>>>
我看不出这些jobs & order部分是如何定义不明确的。那里可能有什么问题?它看起来就像忍者守则中的样子,所以......我很困惑。这些错误与我的期望完全并列,即我输入的道具被 TS 检测到。他们是正确的。
这是props.jobs该行之前的内容computed():
Proxy { <target>: (4) […], <handler>: {…} }
<target>: Array(4) [ {…}, {…}, {…}, … ]
0: Object { title: "bartender", location: "vancouver", salary: 35, … }
1: Object { title: "priest", location: "Calgary", salary: 90, … }
2: Object { title: "Farmworker", location: "Hyrule", salary: 40000, … }
3: Object { title: "potus", location: "USA", salary: 999999, … }
length: 4
如果任何有用的上下文是 MIA,请告诉我。
编辑:在路上很热,我把它改成了computed((props) => ...现在我有一个更好的错误
TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Job'.
42 | console.log("asdfsaf");
43 | return [...props.jobs].sort((a: Job, b: Job) => {
> 44 | return a[props.order] > b[props.order] ? 1 : -1;
| ^^^^^^^^^^^^^^
45 | });
46 | });
编辑以添加我的模板没有 lorem ipsum:
<template>
<div class="jobList">
<h1>Ordered by: {{ order }}</h1>
<ul>
<li v-for="job in x" :key="job.id">
<div class="card">
<div>{{ job.id }}</div>
<h2>{{ job.title }} in the city of {{ job.location }}</h2>
<p>{{ job.salary }} rupees</p>
<div class="description">
lorem ipsum but shorter
</div>
</div>
</li>
</ul>
</div>
</template>
显示../types/Job和../types/OrderTerm:
// Job.ts
interface Job {
title: string,
location: string,
salary: number,
id: string,
ft: boolean
}
export default Job
// OrderTerm.ts
type OrderTerm = "location" | "title" | "salary"
export default OrderTerm