![](/img/trans.png)
[英]Angular 2 TypeScript using es6 Map type in Response DTO type
[英]How to properly handle type for es6 Map<K,V> functions when using Typescript?
我有一个像这样的 class :
export class Broker<T> implements BrokerContract<T> {
topicToSubscribersMap: Map<string, Set<Subscriber<T>>>;
.
.
.
public registerSubscriber(topic: string, subscriber: Subscriber<T>): void {
if (this.topicToSubscribersMap.get(topic)) {
let currentSubscribers: Set<Subscriber<T>> = this.topicToSubscribersMap.get(topic);
}
}
.
.
}
在 function registerSubscriber
中,当我尝试从 map Typescript 中获取值时抱怨我们无法分配V | undefined
V | undefined
到V
,因为Map
上的get
方法返回V | undefined
V | undefined
。
现在,我知道我可以做到——
let currentSubscribers: Set<Subscriber<T>> = <Set<Subscriber<T>>>this.topicToSubscribersMap.get(topic);
或这个 -
let currentSubscribers: Set<Subscriber<T>> = this.topicToSubscribersMap.get(topic) as Set<Subscriber<T>>;
但我担心的是,当我已经在封闭的if
条件中检查undefined
时,为什么还要这样做?
此外,由于这是Map
的get
方法返回V | undefined
的签名本身 V | undefined
的类型,并假设这种情况通常最常出现 - 处理它的最佳方法是什么?
TypeScript 不够聪明,无法缩小 function 调用的结果,因为假定调用不是纯的(即,它可能在具有相同参数的后续调用中返回不同的值)
相反,如果您先分配给变量:
const topic = this.topicToSubscribersMap.get(topic);
if (topic){
// topic is narrowed to Set<Subscriber<T>>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.