Avatar ·

What is null/nil in TypeScript and how to work with it?

Hello everyone! I started learning TypeScript and encountered confusion understanding null and undefined. In JavaScript, I'm used to null being an explicitly assigned 'nothing', and undefined being an uninitialized value. But in TypeScript, is there also a nil type? Or is it the same thing?

Problem: in my project, there's a function that returns data from a database. If a record is not found, I want to return null, but TypeScript complains that the function might return undefined. I tried using strict mode (strictNullChecks: true) and explicitly specifying the return type as string | null, but I still get errors when trying to access the result without checking.

Example code: