admin管理员组文章数量:1122826
I have problem
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] =>
moduleIds.map(m => mapping.get(m).at(0))
.filter(m => m !== undefined)
.map(m => m!);
got
error TS2532: Object is possibly 'undefined'.
What would be the easiest way to use a non-null assertion to tell that a value cannot be null or undefined?
I have problem
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] =>
moduleIds.map(m => mapping.get(m).at(0))
.filter(m => m !== undefined)
.map(m => m!);
got
error TS2532: Object is possibly 'undefined'.
What would be the easiest way to use a non-null assertion to tell that a value cannot be null or undefined?
Share Improve this question asked yesterday Milenko MarkovicMilenko Markovic 611 silver badge6 bronze badges1 Answer
Reset to default 3You could mapping.get(m)!
:
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] =>
moduleIds.map(m => mapping.get(m)!.at(0)).filter(m => m !== undefined)
Playground
A more fast version without the non-null assertion:
export const tfModules = (moduleIds: readonly string[], mapping: Map<string, [string, string]>): string[] =>
moduleIds.reduce((r, m) => {
const found = mapping.get(m);
found && r.push(found[0]);
return r;
}, [] as string[]);
Playground
版权声明:本文标题:typescript - How to refactor my code with non-null assertion? Object is possibly 'undefined' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736281716a1926406.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论