【发布时间】:2020-10-21 04:19:15
【问题描述】:
我正在尝试了解自动类型规则。在这个例子中,我
- 有一个带有可选参数的函数。
- 检查它是否未定义,如果是,请填写一个新值。
- 使用它。
- 最后归还。
第 1、2 和 4 步按预期工作。在第 4 步 typescript 清楚地知道“map”参数不能未定义。但在第 3 步,我必须明确添加一个 !否则我会收到一条错误消息。
代码有效(现在我已经添加了感叹号/断言),但它没有意义。这是 TypeScript 的正确行为吗?我在我的代码中做错了吗? 3 和 4 都指的是同一个变量,而 2 是在它们之前完成的,所以我看不出有什么区别。
function parseUrlArgs(inputString: string, map?: Map<string, string>) : Map<string, string> {
if (!map) {
map = new Map();
}
//map = map??new Map(); // This has the exact same effect as the if statement, above.
// Note: JavaScript's string split would not work the same way. If there are more than two equals signs, String.split() would ignore the second one and everything after it. We are using the more common interpretation that the second equals is part of the value and someone was too lazy to quote it.
const re = /(^[^=]+)=(.*$)/;
// Note: trim() is important on windows. I think I was getting a \r at the end of my lines and \r does not match ".".
inputString.trim().split("&").forEach((kvp) => {
const result = re.exec(kvp);
if (result) {
const key = decodeURIComponent(result[1]);
const value = decodeURIComponent(result[2]);
map!.set(key, value); // Why do I need this exclamation mark?
}
});
return map;
}
我没有更改任何 TypeScript 设置。我使用的是 Deno 内置的默认设置,列出了 here。我在typescript playground 中得到了类似的结果。
【问题讨论】:
标签: typescript deno