我正在学习打字稿中的装饰器。
在那本书中,装饰器是一个简单的函数实现,装饰器只能获取一个参数。
在下面。
function logger(arg:string){
//decorator todo
}
@logger("test")
class TestClass {}
实际上,在Angular中也可以看到这种结构。
所以我转到了Angular中最常用的“组件”的定义。
但是Component的定义是interface。
在“右下方”在Angular中定义为“组件”
directive.d.ts
//also Directive is interface too
export interface Component extends Directive {
changeDetection?: ChangeDetectionStrategy;
....
}
当然,它继承了其他几个接口,但结论是Component的定义是interface。
我在打字稿中使用了相同的示例,而没有使用Angular进行测试。
interface Component{
templateUrl?: string;
template?: string;
styleUrls?: string[];
}
function logger(name:string){
return function(target:Function){
return console.log(`class Name: ${name}`);
}
}
//@logger("BOOK")
@Component({
selector: 'bap-select-cscV2',
templateUrl: './csc-v2.component.html',
styleUrls: ['./csc-v2.component.css']
})
class BOOK{
constructor(private title: string){}
};
我在这里有两个问题。
首先,当我使用@logger将脚本构建到ng-node而不使用@Component时,会记录“类名:书”。
我知道Decorator是元数据。我什至没有创建一个类,但是我不知道记录器为什么起作用。
其次,我不知道为什么接口(名为Component)的行为不像一个角度。
错误是:组件仅引用一种类型,但在此处被用作值。
答案 0 :(得分:1)
logger
装饰器将打印到控制台,因为正在评估该功能。 return console.log(``class name ${name}``);
行得到评估。装饰器与Angular的装饰器有些不同,因为Angular使用reflect-metadata
包来进行反射操作。
您得到的错误是因为您已经声明了一个接口,并试图像初始化它一样使用它。在TypeScript中,定义接口时,该接口仅用于TypeScript找出对象上的类型。编译TypeScript时,不会输出接口。
当您在Angular中查看Component
装饰器的定义是一个接口时,原因是因为它们有意向您隐藏了实现细节。他们称其为Facade
。他们不希望您实际导航到它的代码,而是希望您查看Component
对象的“形状” *。
这通常是类型定义文件.d.ts
,它将告诉TypeScript Angular中所有类型的类型。
*“形状”仅指对象的组成(方法,属性等)