我试图学习如何使用角和打字稿,我是一个视频,直到一个点,他试图使一个方法(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'返回类型应该是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。
From,lib.es2015.core.d.tsfind (谓词:(value:T,index:number,obj:T []) = & gt;unknown,thisArg?:any):T | undefined;
因此,如果 find()方法返回未定义的打字稿将无法将其转换为 Book,这就是错误实际上传达的。
如何修复错误:
非空断言运算符
返回 this.books.find (book = & gt;book.id = = id)!
更新调用函数的返回类型
getBook (id:number):Book | 未定义
Typecast to Book
将 this.books.find (book = & gt;book.id = = id) 返回为 Book
关闭 strictNullChecks(不推荐)不推荐这样做,因为它可能会导致难以跟踪的问题。请访问strictNullChecks了解更多信息
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(43条)