Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

4. What does `!` operator do at the end of variable?

If variable is optional, which means it can also equal undefined, exclamation mark at the end tells compiler that it can be sure the value will always keep some non-undefineed value.

type RandomType = { optionalValue?: string } const rt: RandomType = {optionalValue: "random"}; rt.optionalValue.length // 'rt.optionalValue' is possibly 'undefined'. rt.optionalValue!.length // no error thrown.

In the above example usage of ! is save, because we can be certain that value of optionalValue is always different than undefined.

This operator should be used carefully, because if your value would equal undefined, code is at risk of Cannot read properties of undefined error.

type RandomType = { optionalValue?: string } const rt: RandomType = {}; rt.optionalValue!.length // Cannot read properties of undefined (reading 'length')
Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz