想象一下,你有实现某个装饰器的类:
@Component
class A
@Component
class B
如果你想拥有一个包含某些类的类本身的变量,它会有什么类型?
componentClass: typeof A | typeof B;
但是你有没有想过:当你拥有很多课程时,列举这些课程并不是一种好的做法,当你不了解它们时它甚至都不是一个选择 .
所以剩下的选项是(编辑:因为typescript不允许使用typeof泛型):
componentClass: any;
但这也不好!
I want to define a type guard for this ,所以我可以将 any
类型替换为可以实际检查对象是否具有@Component装饰器的类型,因此可以像这样声明:
componentClass: ComponentClass;
只是一个想法
我认为最好的方法是为它定义一个类型,并在那里定义守卫 . But this is not possible .
@HasDecorator("Component")
type ComponentClass = any;
1 回答
如果您有不同的类代表
Component
,那么为什么不为它们提供基类:然后你有一个所有这些类的类型,不需要类型别名 .
它对装饰器本身也很有用:
甚至:
编辑
你也可以用接口做类似的事情:
2编辑
如果你想传递
ComponentClass
(A
,或B
等),你可以这样做:要么
(code in playground)