[Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator

You can use the non-null assertion operator in TypeScript to take a typed variable and remove the undefined and null types from it. In this lesson, we look at different ways to work around the null/undefined typed values; including as [type] and the use of non-null assertion operator which is as simple as adding an exclamation mark to the end of any given variable while reading the value from it.

 

type User = {
  name: string,
  address?: string 
}

const user = {
  name: "John",
  address: "abc"  
}

const output: string = user.address // because 'address' is optional, it might be null or undefined.

// one way

const output: string = user.address as string

// better way

const output: string = user.address!;

 

posted @ 2021-02-10 17:18  Zhentiw  阅读(88)  评论(0编辑  收藏  举报