简体   繁体   中英

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

I'm trying to get some Angular 11 code working in 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

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

// 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 .

For an example, maybe you can make your props user like this:

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

Now it will working fine.

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