【问题标题】:property 'filter' does not exist on type 'string' in interface接口中的“字符串”类型不存在属性“过滤器”
【发布时间】: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


【解决方案1】:

使用括号将对象与过滤器函数分开

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

【讨论】:

  • 不幸的是它没有帮助,如果只是那样做(entry.newValue as IValue)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2018-10-17
    • 2021-11-27
    • 2017-09-17
    • 2019-04-24
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多