Home > Enterprise >  How to remove non null assertion in typescript?
How to remove non null assertion in typescript?

Time:09-07

i am new to programming and i am trying to remove non-null assertion in the code below,

const children: someData[] = flatten(
  someData
    .filter(({ children }) => children)
    .map(({ children }) => children!) //remove non null assertion operator
);
const nestedChildren = flatten(
  children
    .filter(({ children }) => children)
    .map(({ children }) => children!) //remove non null assertion operator
);

as seen from code above there is non null assertion operator in map method how can i rewrite the code above such that i dont get error "undefined cannot be assigned to type children'

if i remove non null assertion operator i get error like above. could someone help me fix this. thanks.

CodePudding user response:

You need to use custom type guard


const children = [{ children: 42 }, {}]
    .filter((elem): elem is { children: number } => Boolean(elem.children))
    .map(({ children }) => children) 

  • Related