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')
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.