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 badges
Add a comment  | 

1 Answer 1

Reset to default 3

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

本文标签: typescriptHow to refactor my code with nonnull assertion Object is possibly 39undefined39Stack Overflow