[英]Does <ClassName> perform casting in typescript?
The angular DI documentation has the following example: 角度DI文档具有以下示例:
let mockService = <HeroService> {getHeroes: () => expectedHeroes }
Is mockService
now an instance of HeroService
? 是
mockService
现在的实例HeroService
?
Here is another code snippet in case that helps make it clearer: 这是另一个有助于简化说明的代码段:
it('should have heroes when HeroListComponent created', () => {
let hlc = new HeroListComponent(mockService);
expect(hlc.heroes.length).toEqual(expectedHeroes.length);
});
I think mockService
has to be an instance of the HeroService
implementation or interface, because the HeroListComponent
expects such an instance it the constructor. 我认为
mockService
必须是HeroService
实现或接口的实例,因为HeroListComponent
希望构造器可以拥有这样的实例。
No, it is not an instance of HeroService
. 不,它不是
HeroService
的实例。
Let's see a simple example: 让我们看一个简单的例子:
class Point {
x: number;
y: number;
toString() {
return `(${this.x}, ${this.y})`;
}
}
let a = <Point>{ x: 0, y: 0 };
Here a
isn't an instance of Point
, it just has the same members, but if you'll do console.log(a.toString)
you'll get [object Object]
instead of (0, 0)
. 这里
a
不是Point
的实例,它具有相同的成员,但是如果您执行console.log(a.toString)
, console.log(a.toString)
获得[object Object]
而不是(0, 0)
。
You can read more about this here: Type assertions , and also you might want to check out this: Type Compatibility . 您可以在此处阅读有关此内容的更多信息: 键入断言 ,并且您可能还需要查看以下内容: 键入Compatibility 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.