【问题标题】:Vue 3 Typescript not assignable to type ‘[]‘Vue 3 Typescript 不可分配给类型‘[]‘
【发布时间】:2020-11-07 23:58:20
【问题描述】:

我正在尝试在我的数据属性中设置数组的类型,如下所示:

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)
  );

但是 Typescript 返回我以下错误:

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

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

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

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

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

    【讨论】:

    • 如果我这样做 data: () => ({ issues: IssueType = [] }), 我得到以下错误 'IssueType' only refers to a type, but is being used as a value here.
    • @kimfs 你不必那样做,你已经做对了data: () => ({ issues: [] as IssueType[] })。您需要更改的部分是getIssues(projectId: number, label: string): IssueType[]
    猜你喜欢
    • 2021-06-07
    • 2023-02-18
    • 2022-08-23
    • 2018-09-19
    • 2018-09-30
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多