Why Map is not a Map when comming from a Map with ? definition

huangapple go评论53阅读模式
英文:

Why Map is not a Map when comming from a Map with ? definition

问题

I have the following Angular code:

var contactsKV: Map<string, string> = this.deviceContacts.contactList as Map<string, string>;
var newContactsKV: Map<string, string> = new Map<string, string>();
console.log("QQQ" + (contactsKV instanceof Map))
console.log("ZZZ" + (newContactsKV instanceof Map))

Which throws:

QQQfalse
ZZZtrue

I would expect contactsKV to be of type Map. The only difference I can pinpoint in both variables is that contactList is defined optional:

export class Contact {  
  serialNumber?: string
  contactList?: Map<string, string>
}  

And the attribute with the Contact is declared like this:

export class DeviceContactsComponent implements OnInit {
  @Input() viewMode = true;  
  @Input() deviceContacts: Contact= {};//Neither works if I remove '= {}';

Any ideas on why Angular would do this? I need to use Map functions like delete() but they are not recognized in contactsKV as the type seems to be something else.

英文:

I have the following Angular code:

 var contactsKV: Map&lt;string,string&gt; = this.deviceContacts.contactList as Map&lt;string,string&gt;;
 var newContactsKV: Map&lt;string,string&gt; = new Map&lt;string,string&gt;;
 console.log(&quot;QQQ&quot; + (contactsKV instanceof Map))
 console.log(&quot;ZZZ&quot; + (newContactsKV instanceof Map))

Which throws:

QQQfalse
ZZZtrue

I would expect contactsKV to be of type Map. The only difference I can pinpoint in both variables is that contactList is defined optional:

export class Contact {  
  serialNumber?: string
  contactList?: Map&lt;string,string&gt;
}  

And the atribute with the Contact is declared like this:

export class DeviceContactsComponent implements OnInit {
  @Input() viewMode = true;  
  @Input() deviceContacts: Contact= {};//Neither works if I remove &#39;= {}&#39;

Any ideas on why Angular would do this? I need to use Map functions like delete() but they are not recognized in contactsKV as the type seems to be something else.

答案1

得分: 1

While both empty object ({}) and Map are dictionaries, {} is not a Map.

If you want an empty map, create a new one: new Map<string, string>;.

Edit: 看起来您在输入中传递了一个不是地图的对象!

英文:

While both empty object ({}) and Map are dictionnaries, {} is not a Map.

If you want an empty map create a new one : new Map&lt;string,string&gt;;.

Edit: Seems like you were passing an object in input that was not a map !

huangapple
  • 本文由 发表于 2023年5月22日 19:51:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定