arrays - 如何返回提供的数组中包含单个项目的所有项目的数组
问题描述
我正在遵循这些说明:“返回提供的数组中所有知道打字稿的人的数组”
export interface Person {
name: string,
netWorth: number,
coder?: boolean,
us?: boolean
city: string,
languages: string[]
}
export const cities = ['nyc', 'sf', 'la']
export const languages = [
'javascript',
'typescript',
'html',
'css',
'c#',
'python',
'ruby',
]
我认为这很简单:
export function allCodersWhoKnowTypescript(people: Person[]): Person[] {
people = people.filter(languages => languages === ('typescript'))
return people
}
但我得到了错误:
This condition will always return `false` since the types `Person` and `string` have no overlap.
解决方案
从您的代码中,我假设正在使用的语言是 TypeScript 或 JavaScript。
您对人员的匿名功能不正确。匿名函数是用一个包含语言的 person 实例调用的。这就是您收到错误的原因。 languages
在您的语句中是类型Person
,并且永远不会等于字符串。
您还可以将整个过滤器放在 return 语句上,如下所示:
export function allCodersWhoKnowTypescript(people: Person[]): Person[] {
return people.filter(p => p.languages.indexOf('typescript')>=0)
}
上面的代码不会产生任何错误。这确实通过了有限的测试。
推荐阅读
- java - kotlin 类的常量池中的疯狂 UTF-8 条目
- java - Java Bytebuffer 只能顺序读取?
- apache-spark - 如何从大量杂乱的结构化数据中找出模式?
- java - 在什么情况下我们不应该使用依赖注入?
- hangouts-chat - 如何完全删除由 Chat API 创建的 Chat Bot?
- vb.net - VB6 如何使用 VB.NET 的对象数组?
- python - 如何使用计数所有元素并按一个请求分组来进行 pymongo 聚合
- pycharm - 更改文件选项卡颜色 - PyCharm
- reactjs - 如何在 Typescript 中获取提交按钮以将参数发送到我的端点,反应?
- android - 致命异常:java.lang.RuntimeException startPreview 失败