我正在尝试将Angular管道从应用程序重构到库。管道引用了特定类型,但是我想将其转换为使用通用类型,同时保持其当前类型的安全性。
管:
import { Pipe, PipeTransform } from ...
import { MyCustomTypeOne } from ...
import { MyCustomTypeTwo } from ...
import { MyCustomService } from ...
@Pipe({ name: 'customPipe' })
export class CustomPipe implements PipeTransform {
constructor(private myService: MyCustomService) {}
transform(value: MyCustomTypeOne, details: MyCustomTypeTwo): string {
return this.MyCustomService.getResult(
value.customPropertyOne,
value.customPropertyTwo,
details.customPropertyOne
);
}
}
我如何更新此代码,以便在将其移至库时不必引用自定义类型?
更新:
我有一项业务需要不要将类型移动到库中。在文件顶部声明具有特定/泛型属性的类型是否是反模式?这是否可以确保类型安全?
例:
...
interface MyCustomTypeOne {
customPropertyOne: any;
customPropertyTwo: any;
[key: string]: any;
}
interface MyCustomTypeTwo {
customPropertyOne: any;
[key: string]: any;
}
@Pipe({ name: 'customPipe' })
export class CustomPipe implements PipeTransform {
constructor(private myService: MyCustomService) {}
transform(value: MyCustomTypeOne, details: MyCustomTypeTwo): string {
...
这样做的问题是您需要那些类型的某些属性。因此,例如,您有MyCustomTypeOne
和MyCustomTypeTwo
。具体来说,您在.customPropertyOne
和之后.customPropertyTwo
。
这意味着此管道功能只能与存在这些属性的类型一起使用。话虽如此,将它们提取到库的外部只是将模型(MyCustomType*
)迁移到库中而不是库外部的问题。
这意味着在管道功能中唯一要更新的是从中导入模块的位置。
另一件事是您提到使用泛型。我认为您不想在这里使用泛型,因为这更多地涉及返回类型。这有点主观,因为存在一个使用泛型而不实际与输出有任何关系的用例。如果要使用泛型,则可能如下所示:
transform<T, U>(value: T, details: U): string {
return 'something';
}
要么
transform<T>(value: T, details: T): string {
return 'something';
}
但是,请记住,当你做到这一点,T
并且U
是通用的类型。例如,有人可以传入一个Date
对象。这会中断,因为Date
对象没有customPropertyOne
等。要记住的另一件事是,您永远不会显式调用该transform
函数。有角的。因此,您将永远无法真正获得传递通用类型的机会。
我认为您只想将模型移到您的库中,而不是将它们设为“通用”模型
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句