简体   繁体   中英

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[]' .

Use parentheses to separate the object from the filter 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

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. Strings do not have a filter method.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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