arrays - "Not assignable to parameter of type never"Vue存储数组声明TS错误

标签 arrays typescript vue.js vuex typescript-typings

我不明白为什么会出现此错误:

Argument of type '{ id: string; }' is not assignable to parameter of type 'never'.

... 在行 const index = state.sections.findIndex((section) => section.id === id);

在我的 Vue 商店的以下部分:

import { MutationTree, ActionTree, GetterTree } from 'vuex';

interface section {
  id: string;
  section_header: string;
  section_body: string;
  sectionItems: any;
}

interface sections extends Array<section>{}

export const state = () => ({
  sections: [
    {
      id: '1',
      section_header: 'lorem',
      sectionItems: []
    },
    {
      id: '2',
      section_header: 'ipsum',
      sectionItems: []
    }
  ]
});

type EditorState = ReturnType<typeof state>;

export const mutations: MutationTree<EditorState> = {
  ADD_SECTION_ITEM(state, id) {
    const index = state.sections.findIndex((section) => section.id === id);
    const sectionItem = {
      id: randomId()
    }
    state.sections[index].sectionItems.push(sectionItem);
  },
};

最佳答案

当您不为值提供类型时(在本例中为函数的返回值),TypeScript 会尝试将其缩小到最准确的类型。由于您返回的对象的 sections ' 项目数组总是空的,它将它们推断为 never[] ( type[]Array<type> 的别名);一个实际上不能包含任何值的数组。您可以在以下代码段中看到这一点:

const functionReturningEmptyArray = () => ({ items: [] });
type EmptyArray = ReturnType<typeof functionReturningEmptyArray>;
// type EmptyArray = { items: never[] }

解决此问题的一种方法是使用 section您创建的接口(interface),用于指定 state 的返回类型.

export const state = (): { sections: Array<section> } => ({
  sections: [
    {
      id: '1',
      section_header: 'lorem',
      sectionItems: []
    },
    {
      id: '2',
      section_header: 'ipsum',
      sectionItems: []
    }
  ]
});

第一行空括号后的冒号指定函数的返回类型。在这种情况下,我已经内联了对象类型,因为它只有一个属性,但是如果您的 state更复杂,或者如果你只是喜欢可读性,你可以将它提取到一个单独的类型并将其作为返回类型引用;

interface MyState {
    sections: Array<section>;
}

export const state = (): MyState => ({
  sections: [
    {
      id: '1',
      section_header: 'lorem',
      sectionItems: []
    },
    {
      id: '2',
      section_header: 'ipsum',
      sectionItems: []
    }
  ]
});

此时,TypeScript 将对您的返回值抛出错误,因为您的 section接口(interface)指定该对象还应具有 section_body属性,您返回的 sections 中缺少该属性大批。要解决此问题,您可以给数组中的每个对象一个 section_body属性,或修改接口(interface)以匹配属性可能存在或可能不存在的事实;

interface section {
  id: string;
  section_header: string;
  section_body?: string;
  sectionItems: any;
}

您的商店现在应该没有错误,但要有一个更安全的类型 sectionItems属性,您也可以将其更改为 anyArray<any> ,或者如果您事先知道部分项目的外观,则使用更具体的对象类型。

关于arrays - "Not assignable to parameter of type never"Vue存储数组声明TS错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70475907/

相关文章:

vue.js - 如何在 vue.js 中通过点击事件发出一个值

TypeScript:输入递归类型

javascript - 在 Angular 中使用源映射生成生产版本 - CLI

laravel - 将数据从 PHP Twig 传递到 Vue 组件

javascript - 使用其他组件中的按钮显示对话框

angular - 使用 Typescript 在 Angular 中忽略 GET 请求中未定义的属性集

c++ - 为什么这个 'for' 循环无效?

java - 具有不同表达式类型的嵌套开关: ArrayIndexOutOfBoundsException -4

java - 如何计算数组中的唯一元素?只需要想法

arrays - 将一个文本字段中的多个值存储到一个数组中