【发布时间】:2021-08-31 17:18:48
【问题描述】:
我是 typescript 的新手并开始学习它,因为每个人似乎都非常坚持使用 typescript 编码而不是js。所以,试一试,我想我会先将ts 应用于简单的数据结构问题。但是我陷入了以下我似乎没有得到的东西。
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
显示错误:<1> 说Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'
这很令人困惑,因为我将stack 声明为string[],即array of strings,并且我正在检查数组stack 是否与while(stack.length > 0) 不为空。 <2> 说Object is possibly 'undefined',我不确定如何处理这个问题。在js 中,如果它的undefined 则for 循环将不会执行,这是理想的行为。但我不知道如何在ts 中处理这个问题。
【问题讨论】:
-
@Joe 感谢您的回复。所以
<1>似乎是编译器的问题,我想我必须在stack.pop()之后使用!运算符,我觉得这很难看。您对<2>需要做什么有答案或建议。顺便说一句,感谢该链接,它非常有帮助。 -
您的 tsconfig 中是否有一些不寻常的设置?我尝试将您的代码粘贴到 TS Playground typescriptlang.org/play 中,但只收到错误
<1>,而不是错误<2>。 -
@pandubear 感谢您的回复。我不这么认为。我将
target:ES2020、module: commonjs、moduleResolution: node、strict: true和additionalChecks下的所有内容设置为 true(我猜这可能是值得一看的)。noPropertyAccessFromIndexSignature: true现在引起了我的注意,因为你提到了它。是这样吗?我真的不知道它是做什么的,但我喜欢让我的 tsconfig 尽可能严格,所以所有这些都是true。
标签: typescript