簡體   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