首页 > 解决方案 > 如何返回提供的数组中包含单个项目的所有项目的数组

问题描述

我正在遵循这些说明:“返回提供的数组中所有知道打字稿的人的数组”

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.

标签: arraystypescriptarraylistmethodsfiltering

解决方案


从您的代码中,我假设正在使用的语言是 TypeScript 或 JavaScript。

您对人员的匿名功能不正确。匿名函数是用一个包含语言的 person 实例调用的。这就是您收到错误的原因。 languages在您的语句中是类型Person,并且永远不会等于字符串。

您还可以将整个过滤器放在 return 语句上,如下所示:

export function allCodersWhoKnowTypescript(people: Person[]): Person[] {
    return people.filter(p => p.languages.indexOf('typescript')>=0)
    }

上面的代码不会产生任何错误。这确实通过了有限的测试。


推荐阅读