My current setup involves a class structured like this:
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);
}
}
.
.
}
Within the registerSubscriber
function, there is an issue where Typescript raises a complaint about assigning type of V | undefined
to V
because the get
method on Map
returns V | undefined
.
I am aware of two possible solutions -
let currentSubscribers: Set<Subscriber<T>> = <Set<Subscriber<T>>>this.topicToSubscribersMap.get(topic);
or
let currentSubscribers: Set<Subscriber<T>> = this.topicToSubscribersMap.get(topic) as Set<Subscriber<T>>;
However, I find it unnecessary to do this extra check when already verifying for undefined
in the preceding if
statement.
Given that the signature itself of the get
method from Map
specifies a return type of V | undefined
, and considering this scenario might be common with it - what would be the most effective approach to handle such situations?