代码之家  ›  专栏  ›  技术社区  ›  Milenko Markovic

如何使用非空断言重构我的代码?对象可能“未定义”

  •  0
  • Milenko Markovic  · 技术社区  · 6 月前

    我有问题

    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!);
    

    得到了

    error TS2532: Object is possibly 'undefined'.
    

    使用非null断言来告诉值不能为null或undefined的最简单方法是什么?

    1 回复  |  直到 6 月前
        1
  •  2
  •   Alexander Nenashev    6 月前

    你可以 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

    一个没有非空断言的更快版本:

    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