Recently, I decided to delve into typescript after hearing so much praise for it over plain old javascript
. To ease myself into it, I started tackling basic data structure problems using ts
. However, I've hit a roadblock on some concepts that are eluding me.
interface GraphType {
[index: string]: string[];
}
const graph: GraphType = {
a: ['c', 'b'],
b: ['d'],
c: ['e'],
d: ['f'],
e: [],
f: []
}
const depthFirstPrint = (graph: GraphType, source: string) => {
const stack: string[] = [source];
while(stack.length > 0) {
const current: string = stack.pop(); // <1>
console.log(current);
for (let neighbor of graph[current]) { //<2>
stack.push(neighbor);
}
}
};
depthFirstPrint(graph, 'a'); //abdfce
I'm encountering errors at:
<1>
with the message
Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'
The confusion arises as I have defined
stack
as an array of strings and I am also ensuring it's not empty before accessing elements with while(stack.length > 0)
. <2>
brings up Object is possibly 'undefined'
, leaving me uncertain about how to handle this. In traditional js
, if it's undefined
, the loop doesn't run, which is the expected behavior. But I'm unsure how to replicate this in ts
.