为什么Array <mytype> .find(...)返回'MyType |未定义“?

时间:2017-12-13 22:53:53

标签: angular typescript

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

地图

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

BaseObject:

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 Tutorial服务方法

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

我在服务方法的return行上出现的错误是:

  

输入'Observable&lt; Map |未定义&GT;”不能分配给'Observable&lt; Map&gt;'。

我已经下载了教程示例代码,我可以确认.find()方法返回的类型为Hero,而我的代码上的.find()方法返回的类型为{{1} }}

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

1 个答案:

答案 0 :(得分:4)

  

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

选项strictNullChecks

为什么?

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

修复

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

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

更多