简体   繁体   English

Typescript 错误“从不类型上不存在属性 find()”

[英]Typescript error "property find() does not exist on type never"

I'm trying to get some Angular 11 code working in Angular 14:我试图让一些 Angular 11 代码在 Angular 14 中工作:

  users = null;

  deleteUser(id: string)
  {
    if (this.users == null) { }
    else
    {
      const user = this.users.find(x => x.id === id);
      ... other stuff
     }
  }

The error is on the line const user = this.users.find(... It says "property find() does not exist on type 'never'"... why would it think that the type is never? It has already checked that this.users != null错误在线 const user = this.users.find(... 它说“属性 find() 不存在于类型'never'”...为什么它会认为该类型是 never?它已经检查 this.users != null

TS tries to guess the type of vars with the info it has, but it can't always figure it out if no enough typing info or context is present TS 试图用它所拥有的信息来猜测 vars 的类型,但如果没有足够的输入信息或上下文,它就不能总是弄清楚

// Help the compiler when declaring vars
let users: Array<Users> | null = null;


deleteUser(id: string)
  {
    if (this.users !== null) {
      // TS will find the "find" function here,
      // because it knows it's a Users array
      const user = this.users.find(x => x.id === id);
    }
  }

Make sure to define your props type, if you're not define your props type, you will get error type never .确保定义你的道具类型,如果你没有定义你的道具类型,你会得到错误type never

For an example, maybe you can make your props user like this:例如,也许你可以让你的 props user像这样:

user: Array<any>; // if you're sure this is an array

Now in your deleteUser method, you should have not to use if condition, just make it simple like this:现在在您的deleteUser方法中,您应该不必使用 if 条件,只需像这样简单:

deleteUser(id: string): void {
  const user = (this.users || []).find((x) => x.id === id);
  if (!user) return;
  // do some stuff
}

Now it will working fine.现在它将正常工作。

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

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