Reputation: 5155
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:
This made me think, What is !
in typescript signified for?
What happens if it's not passed (optional parameter?) does it throw an error or does it not do anything?
Does it make sense to make argument optional and use !
inside component?
Since filterName
props is optional, what does filterName!
signify?
Can someone explain? Super confused.
Upvotes: 0
Views: 473
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