When I write while
loops, there are times when I know for sure that a certain value exists (connection
in this case), but the control flow analysis is unable to narrow it down. Here's an illustration:
removeVertex(vertex: string) {
const connections = this.adjacencyList[vertex];
while (connections.length) {
const connection = connections.pop(); // <- This value can never be undefined
this.removeEdge(connection!.node, vertex); // <- Avoiding unnecessary casting
}
}
Usually, my go-to solution is simply adding !
to indicate to the compiler that a specific type cannot be undefined. However, I am curious if there is a more elegant approach to addressing this issue.
Edit: adjusted placement of !
as per comments suggestion