Vue 3打字稿无法分配给“ []”类型

时间:2020-11-07 23:58:20

标签: typescript vue.js vuejs3

我正在尝试像这样在我的数据属性中设置数组的类型:

const Projects = defineComponent({
  data: () => ({
    issues: [] as IssueType[]
  }),

我正在调用此方法来过滤数组:

getIssues(projectId: number, label: string): [] {
  return this.issues.filter(
    issue => issue.project_id === projectId && issue.labels?.includes(label)
  );

但是打字稿返回了以下错误:

> Type 'IssueType[]' is not assignable to type '[]'.   Types of property
> 'length' are incompatible.
>     Type 'number' is not assignable to type '0'.

1 个答案:

答案 0 :(得分:3)

在TypeScript中,类型[]明确表示空数组/元组。

type A = [];

const a: A = ['a'];
// Error -> Type '[string]' is not assignable to type '[]'

const a: A = [];
// No error

export default a;

因此,您只需要使用IssueType[]而不是[]显式设置返回类型即可。