为什么不能在类型测试库中使用 'map or filter'?



我不能使用to数组方法来测试库。

我的测试代码如下。

const ListTitle = fakeData.forEach((el) => {
el.filter((element: string | object) => (typeof element === "string" ? element : element?.props?.children));   **** filter method has a error ts.2339
});

附加,我只想排除fakeData数组中的文本。

fakeData类似于下面的代码。

interface FakeDataProps {
id:number
titleChild:JSX.Element
}
const fakeData: FakeDataProps[] = [
{
id: 1,
titleChild: (
<>
party goes on <span style={{ fontWeight: 500 }}> The end</span>
</>
),
},
{
id: 2,
titleChild: (
<>
party goes on <span style={{ fontWeight: 500 }}>The end</span> Your time
is ...{" "}
</>
),
},
{
id: 3,
titleChild: (
<>
party goes on <span style={{ fontWeight: 500 }}>The end</span>
</>
)
}
];

我期待

["派对进行到最后;,"派对继续到最后你的时间是&";,"派对进行到最后;,]

但是,在我的测试代码中,出现了一个错误;类型"FakeDataProps"上不存在属性"filter"。ts(2339(";

我该怎么办?

发生typescript错误是因为您正在对单个项调用.filter()。你应该在这样的项目数组上调用它:


const ListTitle = fakeData.filter((element: string | object) => (typeof element === "string" ? element : element?.props?.children));

在您的示例中不需要.forEach(),只需如上所述使用.filter()即可。

最新更新