AngularTypeScript:“类型'(stringundefined)[]'不能分配给类型'string[]'。”
我正在编写由 Adam Freeman撰写的Pro Angular 9一书。第 8 行抛出错误:
private categories: string[] = [];
错误是
Error: src/app/model/product.repository.ts:13:7 - error TS2322:
Type '(string | undefined)[]' is not assignable to type 'string[]'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Error: src/app/model/product.repository.ts:13:7 - error TS2322:
Type '(string | undefined)[]' is not assignable to type 'string[]'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
我不知道那条线是什么意思。变量如何既是字符串又是数组?
更让我困惑的是,Angular 说错误在第 13 行,而不是第 8 行。这是第 13 行:
除了在带有过滤器的数组上运行映射之外,我不知道该行的作用。
该文件还有两个错误。第 17 行:
this.categories = data.map(p => p.category).filter((c, index, array) => array.indexOf(c) == index).sort();
Type 'null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.
在 JavaScript 中,我会创建一个空字符串:var myString = ''. 在 TypeScript 中,为什么要将字符串设为 null?不是string和nul
getProducts(category: string = null): Product[] {
l不同的类型吗?
第三个错误在第 22 行:
Type 'Product | undefined' is not assignable to type 'Product'.
Type 'undefined' is not assignable to type 'Product'.
我不知道这意味着什么。
这是整个文件:
>这是 这引发了另一个错误: 第 22 行的错误是由于 我去书的GitHub repo下载了最新的文件,和书上的一样。Type 'Product | undefined' is not assignable to type 'Product'.
Type 'undefined' is not assignable to typreturn this.products.find(p => p.id == id);
return this.products.find(p => p.id == id);
product.model.ts:Unexpected token. A constructor, method, accessor, or property was expected.Product类中的错误造成的吗?Product课堂上有什么错误?看起来这个类有一个构造函数。
回答
我不明白告诉明显正在学习的人“关闭严格模式”的价值,因为如果你今天正在学习 Angular 和 Typescript,那么严格的类型检查是一个现实,也是一件非常好的事情。它可以更好地优化构建。此外,还有一些 linting 规则可以防止使用空断言运算符,以帮助您编写可以优化的更好的代码。这本书适用于使用旧版 Typescript 的 Angular 9,并且它们都没有将严格的类型检查强制执行到今天的水平。
这段代码不会因为启用了严格模式而抛出错误——它会抛出错误,因为输入的内容不再正确。这段代码在 Angular 9 中没问题,但在较新的版本中会引发错误。在将旧项目升级到 Angular 10 和 11 时,我也遇到了这些问题,我没有关闭严格模式 - 我修复了代码以使其更好。
这个错误:
不是因为打开了严格模式,而是因为 JavaScript Array 方法undefined在未定义索引时返回。所以这一行
可以返回 aProduct或者undefined如果具有该 ID 的产品不存在。你需要理解并处理它。
这个错误
是因为null是 TypeScript 中的一个类型。您需要正确键入此内容。<
Type 'null' is not assignable to type 'string'.
/p>
应该改为
如果这听起来像咆哮,我很抱歉,因为它不是。当我回答有关 stackoverflow
getProducts(category: string | null = null): Product[] {
的问题时,我会尝试通过教学来更好地理解潜在问题。