首页 > 解决方案 > 错误:无法通过使用数组调用其类型缺少调用签名的表达式

问题描述

我有一个数组,其中有一堆对象:

const standardStories = [
{
    name: 'Executive Summary',
    navLink: 'standard-stories/executive-summary',
    cardIndex: 0,
    storyBoxes: [
        {
            name: 'Chart Box',
            values: commonStdStories.chartBoxValue,
            graphics: commonStdStories.chartBoxGraphic,
        },
        {
            name: 'Financial Chart',
            values: commonStdStories.financialChartValue,
            graphics: commonStdStories.pieChart,
        },
        {
            name: 'Info Progress Bar',
            values: commonStdStories.progressBarValue,
            graphics: commonStdStories.progressBarGraphic,
        },
    ],
},
{
    name: 'High Cost Med',
    navLink: 'standard-stories/hcc-med',
    cardIndex: 2,
    storyBoxes: [
        {
            name: 'Info Progress Bar',
            values: commonStdStories.progressBarValue,
            graphics: commonStdStories.progressBarGraphic,
        },
        {
            name: 'Chart Box',
            values: commonStdStories.chartBoxValue,
            graphics: commonStdStories.chartBoxGraphic,
        },
        {
            name: 'HCC Table',
            value: commonStdStories.hccTable,
        },
    ],
},
{
    name: 'High Cost Rx',
    navLink: 'standard-stories/hcc-rx',
    cardIndex: 3,
    storyBoxes: [
        {
            name: 'Info Progress Bar',
            values: commonStdStories.progressBarValue,
            graphics: commonStdStories.progressBarGraphic,
        },
        {
            name: 'Chart Box',
            values: commonStdStories.chartBoxValue,
            graphics: commonStdStories.chartBoxGraphic,
        },
        {
            name: 'HCC Table',
            value: commonStdStories.hccTable,
        },
    ],
},
]

还有更多,但你明白了。

我正在尝试像这样使用storyBoxes:

standardStories.forEach(story => {
    **story.storyBoxes.forEach(storyBox => {})**
})

在粗体线上是我得到错误的地方[ts] Cannot invoke an expression whose type lacks a call signature只是想知道如何解决这个问题以便我可以继续。理想情况下,我希望能够遍历每个故事,检查每个故事的故事框中列出的每个故事框。

标签: typescript

解决方案


这要看里面的属性是什么类型的commonStdStories。如果内部属性的类型storyBoxes不一致,则 的类型storyBoxes最终可能是数组的联合,您不能将其用作数组,因为方法最终是联合中每种类型的版本的联合。

最简单的解决方案是根据我在问题中看到的内容为常量添加一个明确的类型,这将是一个版本:

interface IStory {

    name: string;
    navLink: string;
    cardIndex: number;
    storyBoxes: Array<{
        name: string;
        value?: string | number;
        values?: string| number; // Typo maybe ? do you want both value and values ?
        graphics?: string| number;
    }>;
}

游乐场链接


推荐阅读