简体   繁体   English

Typescript - 指定破坏变量别名的类型

[英]Typescript - specify type for destructed variable alias

ngOnChanges(changes: SimpleChanges) {
    const {previousValue: prevDate, currentValue: currDate}: SimpleChange = changes.dateFilter;
}

In the above code snippet I want to specify type DateFilter to the prevDate and currDate variables.在上面的代码片段中,我想为prevDatecurrDate变量指定DateFilter类型。 How can I achieve that?我怎样才能做到这一点? I tried like <DateFilter>prevDate and is not working.我试过像<DateFilter>prevDate并且不工作。

You need to cast the type:您需要转换类型:

const prevDate: DateFilter = changes.dateFilte.previousValue as DateFilter

or:或者:

const {previousValue: prevDate, currentValue: currDate} = changes.dateFilter as {previousValue: DateFilter; currentValue: DateFilter };

You can just type the parent object.您只需键入父 object。 Here you can see that types of object properties are inherited to destructored variables myFoo and myBar :在这里您可以看到 object 属性的类型被继承到析构变量myFoomyBar

  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.
    }
  }

And with SimpleChanges something like:使用SimpleChanges类似:

  ngOnChange(c: SimpleChanges) {
    const obj: Obj = c['dateFilter'].currentValue;
    const {foo: foo1, bar: bar1} = obj
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM