【问题标题】:How can I return an array of all items in the provided array that include a singular item如何返回提供的数组中包含单个项目的所有项目的数组
【发布时间】:2020-04-23 01:53:53
【问题描述】:

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

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.

【问题讨论】:

  • 请提及您使用的编程语言。将该编程语言放在标签和标题中将有助于引起人们对您的关注。

标签: arrays typescript arraylist methods filtering


【解决方案1】:

根据您的代码,我假设使用的语言是 TypeScript 或 JavaScript。

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

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

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

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

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多