【发布时间】: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 行上的错误是这样的:
键入'可观察的
我已经下载了教程示例代码,我可以确认.find() 方法返回了Hero 类型,而我的代码中的.find() 方法返回了Map | undefined 类型。
导致这种行为差异的原因是什么?
【问题讨论】:
-
.find可以返回 undefined ,因为数组中的任何项目总是有可能满足您的条件。如果您确信总会有结果,您可以将结果转换为Map。例如:mapArray().find(map => map.ID === id) as Map。我不知道为什么该示例不包括未定义它的返回类型,除非他们在某处手动覆盖find类型签名?编辑:可能他们没有设置--strictNullChecks标志,但你有吗? -
嗯,快速 Ctrl+单击正在工作的
find会显示:find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T | undefined;情节变厚了! -
是的,我猜示例项目没有
strictNullChecks设置,但您的项目有,这可以解释这种行为。在这种情况下,@basarat 的答案应该可以解决您的错误。 -
见鬼,你是对的@CRice!在 Angular 项目中将
"strict":true,添加到tsconfig.json会返回Hero | undefined。就是这样,这就是区别。
标签: angular typescript