Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

null! (non-null assertion operator after null)

I stumbled upon this null! when learning React with TypeScript.

const inputRef = useRef<HTMLInputElement>(null!);

I don’t know why the ! is necessary or what it is doing.

I come from Dart background and if I do this in Dart, it will throw an error. I assume it is similar but works differently from the Dart one.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The ! after anything in TypeScript is generally something that you should avoid. You’ll see most general linting rules throw a warning against using it.

It is used to force TypeScript to think that the value is not null. When the developer is so confident that this value will not be null or undefined when writing their code, they will use the ! operator.

Generally, it’s better to just place a guard statement higher up in your code if something could potentially be null/undefined or use optional chaining instead like this: myPotentiallyUndefinedObject?.name || 'fallback'.

In your specific question about using null!, that just makes zero sense to use because you shouldn’t be confidently saying that null will never be null because it’s clearly null.

Just say const inputRef = useRef<HTMLInputElement | null>(null); without the ! and let TypeScript know that the value could be null. Then TypeScript will be much nicer to work with in the rest of your component.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading