【发布时间】:2021-06-09 04:44:56
【问题描述】:
我正在编写一个 React 应用程序(在 TypeScript 中),其中我有两个 useState 对象,用于判断是否从产品中删除了插件/附件,以用于视觉目的。产品可以同时包含附件和插件。
首先要做的事情。我有两个不同的插件和附件界面:
interface IAddon {
id: string;
// some other values
}
interface IAccessory {
id: string;
// some other values
}
我上面的两个接口都包含在一个称为产品的父接口中:
interface IProduct {
rowId: string;
accessories: IAccessory[];
addons: IAddon[];
// other values
}
我创建了两个 useStates,它们可以包含按产品键排序的非活动附件和插件列表,因为我有一个用户可以添加或删除附件或插件的产品列表。一旦产品处于非活动状态,它的视觉效果就会发生变化。
interface IAddonsWithId {
[rowId: string]: IAddon[]
}
interface IAccessoriesWithId {
[rowId: string]: IAccessory[]
}
我正在尝试创建一个适用于上述两个接口的密钥对函数,并且可以从其中任何一个接口中添加或删除。我有下面提到的 useStates。
const [inactiveAddons, setInactiveAddons] = useState<IAddonsWithId>({});
const [inactiveAccessories, setInactiveAccessories] = useState<IAccessoriesWithId>({});
我已经创建了这个小接口来处理以下函数:
interface IKeyPair {
rowId: string;
objectId: string;
object: IAddonsWithId | IAccessoriesWithId;
}
因此,我正在尝试创建此功能:
const sortOutObjectFromList = ({rowId, objectId, object}: IKeyPair) => {
return {
...object,
[rowId]: object[rowId].filter( // <--- This line troubles me (TS:2349)
(item: IAddon | IAccessory) => item.id !== objectId,
),
};
};
该功能的想法是能够运行我的插件和附件列表,并能够整理出应该删除它的非活动状态的项目。我将不得不创建一个类似的函数来将项目添加到非活动列表中,但首先我需要弄清楚如何满足 TSLint。
我在上面标记的行上收到以下错误:
TS2349: This expression is not callable. Each member of the union type '{ <S extends IAddon>(callbackfn: (value: IAddon, index: number, array: IAddon[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: IAddon, index: number, array: IAddon[]) => unknown, thisArg?: any): IAddon[]; } | { ...; }' has signatures, but none of those signatures are compatible with each other.
我的代码应该是可编译的,但我想避免 TSLint 错误,因为我已经设置了预提交挂钩来检查它。我已经尝试在 stackoverflow 上搜索 google 和 here,但无法完全弄清楚如何修复此错误。
我认为问题在于IAddon 和IAccessory 两个接口的混合,因为它们不共享许多相同的属性,除了id。这是我唯一尝试匹配的。
如何消除此 TSLint 错误?
【问题讨论】:
-
你怎么调用 sortOutObjectFromList 函数
-
这个想法是调用函数如下:
setInactiveAddons(sortOutObjectFromList({rowId, objectId, inactiveAddons}))。rowId和objectId是从被点击的对象中提取出来的。
标签: reactjs typescript interface use-state