【问题标题】:type 'Book' unassignable to type 'Book' [closed]类型“书”不可分配为类型“书”[关闭]
【发布时间】:2021-09-15 03:32:45
【问题描述】:

我正在尝试学习如何使用 angular 和 typescript,我一直在关注一个视频,直到他试图制作一个方法 (getBookId),该方法应该获取一个书籍 ID,然后签入一个数组并返回其有相同 id 的书时的信息。

this is the repository.model.ts with method thats causing the error it says: Type 'Book | undefined' is not assignable to type 'Book'. Type 'undefined' is not assignable to type 'Book'

【问题讨论】:

标签: angular typescript visual-studio-code


【解决方案1】:

返回类型应该是Book | undefined,因为如果没有找到匹配的书,find 方法可以返回 undefined。

Documentation 供参考。

getBookId(id: Number): Book | undefined {
  return this.books.find(book => book.id === id);
}

【讨论】:

    【解决方案2】:

    由于您只说明了您的打字稿错误而不是您的问题,我假设您想知道为什么会收到此错误并想要修复它。

    Type 'Book | undefined' is not assignable to type 'Book'.
      Type 'undefined' is not assignable to type 'Book'
    

    错误来自Array.prototype.find() 方法。来自MDN

    find() 方法返回第一个元素的值 提供的数组满足提供的测试功能。如果不 值满足测试函数,返回undefined。

    发件人,lib.es2015.core.d.ts

    find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: 任意): T |未定义;

    在您的情况下 T = Book,因此 find() 将返回 Book 类型的对象或未定义的对象,但您的 getBookId() 方法返回 Book。因此,如果 find() 方法返回未定义的 typescript 将无法将其转换为 Book,这就是错误实际传达的内容。

    如何修复错误:

    1. 非空断言运算符

      返回 this.books.find(book => book.id == id)!

    2. 更新调用函数的返回类型

      getBook(id: number): 书 |未定义

    3. Typecast to Book

      将 this.books.find(book => book.id == id) 返回为 Book

    4. 关闭 strictNullChecks(不推荐) 不建议这样做,因为它可能导致难以跟踪问题。 在strictNullChecks了解更多信息

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2014-09-16
      • 2020-04-02
      • 2019-06-02
      • 2011-05-08
      • 2015-09-13
      • 2018-01-04
      • 2020-11-09
      • 1970-01-01
      相关资源
      最近更新 更多