簡體   English   中英

Typescript 錯誤“從不類型上不存在屬性 find()”

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

我試圖讓一些 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
     }
  }

錯誤在線 const user = this.users.find(... 它說“屬性 find() 不存在於類型'never'”...為什么它會認為該類型是 never?它已經檢查 this.users != null

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

確保定義你的道具類型,如果你沒有定義你的道具類型,你會得到錯誤type never

例如,也許你可以讓你的 props user像這樣:

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

現在在您的deleteUser方法中,您應該不必使用 if 條件,只需像這樣簡單:

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

現在它將正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM