typescript

How to refactor my code with non-null assertion? Object is possibly '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?


Solution

  • You 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