【发布时间】:2021-09-15 03:32:45
【问题描述】:
我正在尝试学习如何使用 angular 和 typescript,我一直在关注一个视频,直到他试图制作一个方法 (getBookId),该方法应该获取一个书籍 ID,然后签入一个数组并返回其有相同 id 的书时的信息。
【问题讨论】:
标签: angular typescript visual-studio-code
我正在尝试学习如何使用 angular 和 typescript,我一直在关注一个视频,直到他试图制作一个方法 (getBookId),该方法应该获取一个书籍 ID,然后签入一个数组并返回其有相同 id 的书时的信息。
【问题讨论】:
标签: angular typescript visual-studio-code
返回类型应该是Book | undefined,因为如果没有找到匹配的书,find 方法可以返回 undefined。
Documentation 供参考。
getBookId(id: Number): Book | undefined {
return this.books.find(book => book.id === id);
}
【讨论】:
由于您只说明了您的打字稿错误而不是您的问题,我假设您想知道为什么会收到此错误并想要修复它。
Type 'Book | undefined' is not assignable to type 'Book'.
Type 'undefined' is not assignable to type 'Book'
错误来自Array.prototype.find() 方法。来自MDN,
find() 方法返回第一个元素的值 提供的数组满足提供的测试功能。如果不 值满足测试函数,返回undefined。
find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: 任意): T |未定义;
在您的情况下 T = Book,因此 find() 将返回 Book 类型的对象或未定义的对象,但您的 getBookId() 方法返回 Book。因此,如果 find() 方法返回未定义的 typescript 将无法将其转换为 Book,这就是错误实际传达的内容。
如何修复错误:
非空断言运算符
返回 this.books.find(book => book.id == id)!
更新调用函数的返回类型
getBook(id: number): 书 |未定义
Typecast to Book
将 this.books.find(book => book.id == id) 返回为 Book
关闭 strictNullChecks(不推荐) 不建议这样做,因为它可能导致难以跟踪问题。 在strictNullChecks了解更多信息
【讨论】: