说服TSC匹配数组元素是已知的定义



考虑

function match(s: string): string {
let m;
if ((m = /<(wi+b*le)>/.exec(s)) !== null) {
return m[1];  // [2332] Type 'string | undefined' is not assignable to type 'string'.
}
return "no match";
}

人类可以看到,如果regexp完全匹配,组#1肯定会捕获文本,因此m[1]不会是undefined,但TSC不知道这一点,并抛出错误。

假设项目策略禁止使用非null断言(后缀!(,那么将m[1]转换为可以从该函数返回的东西的推荐方法是什么?

可选链接运算符(?.(和Nullish合并运算符(??(的组合应该适用于您:

TS游乐场

function match(s: string): string {
return (/<(wi+b*le)>/).exec(s)?.[1] ?? 'no match';
}

function match(s) {
return (/<(wi+b*le)>/).exec(s)?.[1] ?? 'no match';
}
console.log(match('<wiiiiiiile>')); // "wiiiiiiile"
console.log(match('other')); // "no match"

最新更新