![](/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.