[英]property 'filter' does not exist on type 'string' in interface
I have interfaces:我有接口:
export interface ISomeInterface {
id: string;
action: string;
newValue: IValue[] | string;
oldValue: IValue[] | string;
}
interface IValue {
id: string
name: string
}
and I try to call methods for array filter:我尝试调用数组过滤器的方法:
const entry: ISomeInterface;
let result = entry.newValue.filter(({ id }) => !entry.oldValue.find((el) => el.id === id))
And get error: Property 'filter' does not exist on type 'string | IValue[]'
并得到错误:
Property 'filter' does not exist on type 'string | IValue[]'
Property 'filter' does not exist on type 'string | IValue[]'
. Property 'filter' does not exist on type 'string | IValue[]'
。
Use parentheses to separate the object from the filter function使用括号将 object 与过滤器function 分开
let result = (entry.newValue).filter(({ id }) =>.entry.oldValue.find((el) => el.id === id))
trying to judge the type of newValue at first, and if it is an array, you can then use filter首先尝试判断newValue的类型,如果是数组,则可以使用filter
You are getting this error because filter
is a method that's available only for arrays and you've set your newValue
property to be an array of strings OR a string.您收到此错误是因为
filter
是一种仅适用于 arrays 的方法,并且您已将newValue
属性设置为字符串数组或字符串。 Strings do not have a filter
method.字符串没有
filter
方法。
As the above comment correctly points in the right direction, use parentheses to separate the object from the filter
function AND set the type as follows:由于上述注释正确指向正确的方向,请使用括号将 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.