繁体   English   中英

接口中的“字符串”类型不存在属性“过滤器”

[英]property 'filter' does not exist on type 'string' in interface

我有接口:

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[]' Property 'filter' does not exist on type 'string | IValue[]'

使用括号将 object 与过滤器function 分开

let result = (entry.newValue).filter(({ id }) =>.entry.oldValue.find((el) => el.id === id))

首先尝试判断newValue的类型,如果是数组,则可以使用filter

您收到此错误是因为filter是一种仅适用于 arrays 的方法,并且您已将newValue属性设置为字符串数组或字符串。 字符串没有filter方法。

由于上述注释正确指向正确的方向,请使用括号将 object 与filter function 分开并设置类型如下:

let result = (entry.newValue as string[]).filter(({ id }) => !entry.oldValue.find((el) => el.id === id))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM