【发布时间】:2021-06-21 08:06:31
【问题描述】:
我有接口:
export interface ISomeInterface {
id: string;
action: string;
newValue: IValue[] | string;
oldValue: IValue[] | string;
}
interface IValue {
id: string
name: string
}
我尝试调用数组过滤器的方法:
const entry: ISomeInterface;
let result = entry.newValue.filter(({ id }) => !entry.oldValue.find((el) => el.id === id))
然后得到错误:Property 'filter' does not exist on type 'string | IValue[]'。
【问题讨论】:
-
你应该有一个单一的类型。但为了快速解决问题,不妨试试
(entry.newValue as IValue[]).filter... -
过滤器在字符串类型上不存在。由于 newValue 既可以是数组也可以是字符串,所以 TS 会抛出这个错误。
-
过滤器不存在于字符串中。 newValue 可以是 IValue 和字符串的数组吗?
-
@Emilien 它有效,谢谢。但你是对的,我应该使用单一类型重写以下内容!
标签: javascript angular typescript interface