![](/img/trans.png)
[英]TypeScript - specify type while object destructuring with alias
[英]Typescript - specify type for destructed variable alias
ngOnChanges(changes: SimpleChanges) {
const {previousValue: prevDate, currentValue: currDate}: SimpleChange = changes.dateFilter;
}
在上面的代碼片段中,我想為prevDate
和currDate
變量指定DateFilter
類型。 我怎樣才能做到這一點? 我試過像<DateFilter>prevDate
並且不工作。
您需要轉換類型:
const prevDate: DateFilter = changes.dateFilte.previousValue as DateFilter
或者:
const {previousValue: prevDate, currentValue: currDate} = changes.dateFilter as {previousValue: DateFilter; currentValue: DateFilter };
您只需鍵入父 object。 在這里您可以看到 object 屬性的類型被繼承到析構變量myFoo
和myBar
:
obj: Obj = { foo: 4, bar: '1'};
ngOnInit() {
const {foo: myFoo, bar: myBar} = this.obj;
if (myFoo === '3') {
// his condition will always return 'false' since the types 'number' and '"3"' have no overlap.
}
}
使用SimpleChanges類似:
ngOnChange(c: SimpleChanges) {
const obj: Obj = c['dateFilter'].currentValue;
const {foo: foo1, bar: bar1} = obj
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.