我有一个模拟AngularActivatedRouteSnapshot
的对象(参见定义(。所有的道具都被模拟出来了。然后,我通过将第一个对象的道具扩展到第二个对象来创建另一个模拟对象。
export class AddEditResolverMocks {
static routeWithId: ActivatedRouteSnapshot = {
params: { id: 123 },
data: { entity: EntityTypes.PayBillCycle },
url: [],
queryParams: {},
fragment: '',
outlet: '',
component: '',
routeConfig: null,
root: new ActivatedRouteSnapshot(),
parent: new ActivatedRouteSnapshot(),
firstChild: new ActivatedRouteSnapshot(),
children: [],
pathFromRoot: [],
paramMap: null,
queryParamMap: null,
};
static routeWithoutId: ActivatedRouteSnapshot = {
...this.routeWithId,
};
}
我以为它会带来所有的道具,但VSCode似乎抱怨道:
Type '{
url: UrlSegment[];
params: Params;
queryParams: Params;
fragment: string;
data: Data;
outlet: string;
component: string | Type<any>;
routeConfig: Route;
}' is missing the following properties from type 'ActivatedRouteSnapshot':
- root,
- parent,
- firstChild,
- children,
- and 3 more.ts(2740)
当我让VSCode重构它时;缺少";道具被添加,错误就消失了。那么,为什么它在没有显式初始化的情况下不起作用呢?(感觉我错过了一些愚蠢的东西(
我还对VSCode允许在静态初始化器中引用this
感到惊讶。
更新:将this
更改为AddEditResolverMocks
:
static routeWithoutId: ActivatedRouteSnapshot = {
...AddEditResolverMocks.routeWithId,
};
没有效果。
更新2:根据注释在desc中添加了ActivatedRouteSnapshot的定义。
问题是这些丢失的属性不存在于ActivatedRouteSnapshot类的定义中。它们实际上是getter,而不是属性。
然而,当存在没有等效setter的getter属性时;编译器"假设这是只读的,这迫使您以创建对象实例的方式通知此属性。
但是,即使您已经通知了此特定实例中的属性,routeWithId变量定义仍然是ActivatedRouteSnapshot,它没有这些属性。
为了使错误消失,只需删除变量的定义:
export class AddEditResolverMocks {
static routeWithId = {
params: { id: 123 },
data: { entity: EntityTypes.PayBillCycle },
url: [],
queryParams: {},
fragment: '',
outlet: '',
component: '',
routeConfig: null,
root: new ActivatedRouteSnapshot(),
parent: new ActivatedRouteSnapshot(),
firstChild: new ActivatedRouteSnapshot(),
children: [],
pathFromRoot: [],
paramMap: null,
queryParamMap: null,
};
static routeWithoutId: ActivatedRouteSnapshot = {
...this.routeWithId,
};
}
不过,我建议您不要以这种方式实例化这些对象。最合适的是使用new
运算符并通过构造函数传递参数。
另外,因为构造函数在接收这些参数时会执行一些操作,所以在以这种方式实例化时不会执行这些操作。并且您插入的额外属性不应该存在于这个类中。