Markus
Markus

Reputation: 1211

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

Upvotes: 0

Views: 793

Answers (2)

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

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 users like this:

users: Array<any>; // if you're sure this is an array (edited var name)

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.

Upvotes: 1

Guille L&#243;pez
Guille L&#243;pez

Reputation: 73

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
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);
    }
  }

Upvotes: 1

Related Questions