简体   繁体   English

打字稿:类型不可分配给类型

[英]Typescript : Type is not assignable to type

I'm getting the below error for this TypeScript code :我收到此 TypeScript 代码的以下错误:

getTollById(id: number): Toll {
  return this.toll
    .filter(toll => toll.id === id)
    .pop();

}

 

👋🏻 @DarBen, 👋🏻@DarBen,

The array method, filter , returns an array inferred from the instance.数组方法filter返回从实例推断的数组。 This could return an empty array.这可能会返回一个空数组。 When using pop() on an empty array, you will get undefined as seen here .当使用pop()返回一个空数组,你会得到undefined所看到这里

Also, the use of pop will not affect the list of TODOs.此外,使用pop不会影响 TODO 列表。 I'm not sure if you were thinking the todos array would be affected?我不确定您是否认为 todos 数组会受到影响? The first playground link demonstrates that.第一个游乐场链接演示了这一点。

If you are just looking to find the todo in the list, you can use the find method, which does the same as filter followed by pop , but IMO shows that you are looking for an item without the ambiguity that the original array might be affected.如果你只是想在列表中找到待办事项,你可以使用find方法,它与filter后跟pop的作用相同,但 IMO 显示你正在寻找一个没有歧义的项目,原始数组可能会受到影响. Here is a complete example . 这是一个完整的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM