TypeScriptBasic types
null and undefined
The types for the absence of a value, controlled by strictNullChecks.
Example
#TypeScript
function findUser(id: number): { name: string } | null {
return id === 1 ? { name: 'Emma' } : null
}
const user = findUser(2)
console.log(user?.name ?? 'Guest')
console.log(findUser(1)?.name)Result
Guest Emma
Definition and usage
#In TypeScript, null and undefined have their own types. With the strictNullChecks option turned on (part of strict mode), you can’t assign them to a variable typed string or number. If a value might not exist, you have to say so explicitly: string | null.
That way the compiler forces you to handle the missing value. Before you read a property, you have to check that the object exists, or use the ?. and ?? operators.
A convention in many projects: undefined means “not set” (for example an omitted optional field), and null means “deliberately empty” (for example no avatar).
Syntax
#Syntax
let value: string | null = null
let optional: number | undefinedMore examples
#TypeScript
const avatar: string | null = null
console.log(avatar.length)
// Error: 'avatar' is possibly 'null'.Good practices
#- Keep
strictNullChecksturned on. It’s one of the most valuable protections against “cannot read properties of undefined” errors. - The
??operator returns the right-hand side only fornullandundefined, not for0or an empty string.
Related entries
#Spotted a mistake or missing an example? Write to us.