【问题标题】:Why does Array<MyType>.find(...) return 'MyType | undefined'?为什么 Array<MyType>.find(...) 返回 'MyType |不明确的'?
【发布时间】:2017-12-14 07:58:37
【问题描述】:

我正在使用 TypeScript 构建一个 Angular 应用程序。我有以下具有与属性完全匹配的相应接口的类:

地图:

export class Map extends BaseObject implements IMap {
    Dimensions: Dimension[];
    Shapes: Shape[];
    Roles: Role[];
}

基础对象:

export class BaseObject implements IBaseObject {
    ID: string;
    Label: string;
    DataType: string;
    CreatedDate: Date;
    CreatedUser: string;
    UpdatedDate: Date;
    UpdatedUser: string;
}

我有以下服务方法,其中mapArray() 是一个模拟 Map 对象数组的函数(返回类型明确声明为Map[]):

我的服务方式:

getMap(id: string): Observable<Map> {
    return of(mapArray().find(map => map.ID === id));
}

此代码几乎是从Angular tutorial example 大量提取的:

Angular 教程服务方法:

getHero(id: number): Observable<Hero> {
  this.messageService.add(`HeroService: fetched hero id=${id}`);
  return of(HEROES.find(hero => hero.id === id));
}

我的服务方法的return 行上的错误是这样的:

键入'可观察的' 不可分配给类型 'Observable'。

我已经下载了教程示例代码,我可以确认.find() 方法返回了Hero 类型,而我的代码中的.find() 方法返回了Map | undefined 类型。

导致这种行为差异的原因是什么?

【问题讨论】:

  • .find 可以返回 undefined ,因为数组中的任何项目总是有可能满足您的条件。如果您确信总会有结果,您可以将结果转换为Map。例如:mapArray().find(map =&gt; map.ID === id) as Map。我不知道为什么该示例不包括未定义它的返回类型,除非他们在某处手动覆盖 find 类型签名?编辑:可能他们没有设置--strictNullChecks 标志,但你有吗?
  • 嗯,快速 Ctrl+单击正在工作的 find 会显示:find(predicate: (value: T, index: number, obj: T[]) =&gt; boolean, thisArg?: any): T | undefined; 情节变厚了!
  • 是的,我猜示例项目没有 strictNullChecks 设置,但您的项目有,这可以解释这种行为。在这种情况下,@basarat 的答案应该可以解决您的错误。
  • 见鬼,你是对的@CRice!在 Angular 项目中将 "strict":true, 添加到 tsconfig.json 会返回 Hero | undefined。就是这样,这就是区别。

标签: angular typescript


【解决方案1】:

导致这种行为差异的原因是什么?

选项strictNullChecks

为什么?

因为Array.prototype.find 确实返回undefined

修复

如果你知道你肯定会找到它,你可以使用断言:

getMap(id: string): Observable<Map> {
    return of(mapArray().find(map => map.ID === id)!);
}

更多

【讨论】:

  • 谢谢@basarat,它并不能完全回答行为上的差异,但你的回答让我思考为什么我试图复制这种行为而不是正确处理它——也就是说我应该处理无法找到指定 ID 的项目的情况。
  • `它并不能完全回答行为上的差异`选项strictNullChecks是答案中提到的差异?
  • 感谢您的厚颜无耻的编辑;)对于其他所有人,可以通过在compilerOptions 下设置"strict": true 来设置tsconfig.json
  • 是的,对不起。在您发表评论后,我再次查看了答案?
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多