TechnoCorner
TechnoCorner

Reputation: 5155

Understanding ! operator in typescript

I'm very new to typescript and I'm trying to learn the language.

I'm reading through a component and I see this:

interface FilterRowProps {
  cannotRemove: boolean
  filterName?: string
}

const field = getField(demo.fields)(filterName!)

Questions:

Since filterName props is optional, what does filterName! signify?

Can someone explain? Super confused.

Upvotes: 0

Views: 473

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85022

The ! is the non-null assertion operator. It tells typescript "i know this looks like it might be null/undefined, but trust me, it's not". This is occasionally needed in cases where typescript can't figure out that your code eliminates the possibility of a null or undefined.

But be aware that like any type assertion, you are telling typescript not to check your work. If you use it, and it actually can be null/undefined, typescript will not alert you to this fact, and you may get an error at runtime.

In short: you should rarely use this. Most of the time, if the types lead typescript to deduce that it might be undefined, then it's probably right. You should then write code to deal with the undefined.

Upvotes: 5

Related Questions