如果我們在當前Component的ngOnChanges鉤子的SimpleChanges typescript參數內進行類型檢查,那將會很棒。在ngOnChanges鉤子中對SimpleChanges接口進行類型檢查
這樣可以防止我們檢查屬性中的錯誤。
如果我們在當前Component的ngOnChanges鉤子的SimpleChanges typescript參數內進行類型檢查,那將會很棒。在ngOnChanges鉤子中對SimpleChanges接口進行類型檢查
這樣可以防止我們檢查屬性中的錯誤。
使用打字稿2.1和keyof功能我已經想通了以下類型聲明(基於SimpleChanges),這似乎給我們必要的類型訪問組件的屬性:
export type ComponentChange<T, P extends keyof T> = {
previousValue: T[P];
currentValue: T[P];
firstChange: boolean;
};
export type ComponentChanges<T> = {
[P in keyof T]?: ComponentChange<T, P>;
};
使用這些聲明vscode編輯器自動獲取類型信息並自動完成更改屬性:
雖然一個問題是,更改參數現在將列出組件的每個屬性(而不僅僅是@Input()屬性),但我沒有找到比這更好的方法。
我使用繼承來解決問題。首先,我創建了擴展SimpleChange類的類型化接口。您只需要執行一次並將其導入需要它的組件。
interface TypedChange<T> extends SimpleChange
{
previousValue: T;
currentValue: T;
}
第二,我們擴展SimpleChanges接口,使其中的元件有望改變。例如
interface MyComponentChanges extends SimpleChanges
{
RefreshQueue: TypedChange<number>
}
最後實現是
public ngOnChanges(changes: MyComponentChanges): void
{
if (changes.RefreshQueue)
{
if (!changes.RefreshQueue.isFirstChange())
{
if (changes.RefreshQueue.currentValue == 1)
{
DoSomething();
}
}
}
}
智能感知屏幕截圖如下
我不知道你貼的權利網站上... – trichetriche
使用繼承即使你可以迭代所有的輸入,並不是所有的輸入都可能必然發生變化。擴展簡單更改界面將顯示組件期望更改的輸入。無論如何,只是我的2美分。 – Ashg