javascript - 如何在沒有特定類型的情況下更新 Angular 管道
我正在嘗試將應用程式中的 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 {
...
答案#1
這個問題在於你關注的是那些類型的某些屬性。因此,例如,你有 MyCustomTypeOne 和 MyCustomTypeTwo。具體來說,你關注的是 .customPropertyOne 和 .customPropertyTwo。
這意味著這個 pipe 函數只能與那些具有這些屬性的類型一起使用。也就是說,將這些屬性提取到庫外部只是將你的模型(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 函數。Angular 會調用它。所以,你實際上永遠沒有機會傳入你的通用類型。
我認為你只是想把你的模型移到你的庫中,而不是讓它們變得「通用」
答案#2
類型可以是此管道範圍內庫的一部分。
我建議在管道內部創建類型,或者通過管道創建類型,然後將它們一起移到庫中。
此外,還有一個選項可以使用 any 來取代你的特定類型,但我不建議這麼做
