Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript null and undefined

TypeScript null and undefined

In TypeScript, null and undefined have special handling.

Enabling strictNullChecks After that, you need to handle these values explicitly, which helps write safer code.


null and undefined handling null means "null value" requires explicit declaration string | null vs undefined means "undefined" automatically included in optional properties name?: string Safe Safe handling methods Optional chaining: obj?.prop Nullish coalescing: value ?? default Type guard: if (val !== null) Handling scenarios Union type declarations Optional parameters and properties Nullish coalescing operator

Why null and undefined need handling

In JavaScript, null and undefined are common sources of errors, and many runtime errors are related to them.

TypeScript's strictNullChecks option requires developers to explicitly handle values that may be null.

Although this increases the coding workload, it can greatly reduce runtime errors caused by null values and improve code reliability.

Concept explanation:null means "null value", that is, there is no value here;undefined means "undefined", that is, no value has been assigned here yet.


Basics of null and undefined

null means "null value", and undefined means "undefined". The two are independent types in TypeScript.

Example

// Declare a variable of type null

// Can only be assigned null

var

empty

:

null

=

null

;

// Declare a variable of type undefined

// Can only be assigned undefined

var

notDefined

:

undefined

=

undefined

;

console.

log

(

"null: "

empty

)

;

console.

log

(

"undefined: "

notDefined

)

;

Running result:

null: null

undefined: undefined

Explanation:Without strictNullChecks enabled, these types can be assigned to each other. Once enabled, explicit declaration is required.


Handling null with union types

After enabling strictNullChecks, union types are needed to explicitly declare values that may be null.

Example

// Union type: can be a string or null

// Explicitly declare that the value may be null

var

name

:

string

|

null

=

"Alice"

;

name

=

null

;

 

// Correct: can be assigned null

// Accessing a possibly null value requires a check first

// Function parameter may be a string or null

function

getLength

(

str

:

string

|

null

)

:

number

{

   

// Use a conditional check for null

   

if

(

str

===

null

)

{

       

return

0

;

 

// Return 0 when null

   

}

   

// TypeScript infers that str is not null

   

return

str.

length

;

}

console.

log

(

"Length: "

getLength

(

"hello"

)

)

;

console.

log

(

"Length: "

getLength

(

null

)

)

;

Running result:

长度: 5

长度: 0

Best practices:Use a type guard (if check) to narrow the type so TypeScript knows the specific type.


Optional parameters and properties

Optional parameters and optional properties automatically include undefined, so there is no need to explicitly declare null.

Example

// Optional parameter: marked with ?

// The parameter may be string or undefined

function

greet

(

name

?:

string

)

:

string

{

   

// Check whether it is undefined

   

if

(

name

===

undefined

)

{

       

return

"Hello, stranger!"

;

   

}

   

return

"Hello, "

name

;

}

console.

log

(

greet

(

"Alice"

)

)

;

console.

log

(

greet

(

)

)

;

// Optional property: marked with ?

// The age property is optional and may not exist

interface

User

{

    name

:

string

;

    age

?:

number

;

 

// Optional property

}

var

user

:

User

=

{

name

:

"Bob"

}

;

console.

log

(

"User: "

JSON.

stringify

(

user

)

)

;

Running result:

Hello, Alice!

Hello, stranger!

用户: {"name":"Bob"}

Explanation:Optional arguments name?: string is equivalent to string | undefined。


Non-null assertion operator

Use ! Tells the compiler that the value is not null or undefined. This should be used with caution.

Example

function

getLength

(

str

:

string

|

null

)

:

number

{

   

// Non-null assertion: tell the compiler that str is not null

   

// This is a dangerous practice; if str is really null, an error will occur

   

return

str

!

.

length

;

}

console.

log

(

"Length: "

getLength

(

"hello"

)

)

;

Warning:Non-null assertions bypass TypeScript's type checking; if the value is actually null, a runtime error will still occur. Try to avoid using them.


Nullish coalescing operator

Use ?? Provides a default value, which is used only when the value is null or undefined.

Example

// Initial value is null

var

name

:

string

|

null

=

null

;

// The ?? operator: use the right-hand value when the left is null/undefined

// If name is null, use "Guest"

var

displayName

=

name

??

"Guest"

;

console.

log

(

"Display name: "

displayName

)

;

// Compare with the || operator (which treats 0 and empty strings as falsy)

var

num

:

number

|

null

=

0

;

var

result1

=

num

??

100

;

 

// 0 (correct: 0 is not null/undefined)

var

result2

=

num

||

100

;

 

// 100 (error: 0 is treated as falsy)

console.

log

(

"?? result: "

result1

)

;

console.

log

(

"|| result: "

result2

)

;

Running result:

显示名称: Guest

?? 结果: 0

|| 结果: 100

Note:Priority use ?? instead of ||, because ?? Only handles null and undefined, and does not mistakenly treat 0 or empty strings as falsy.


Optional Chaining

Use ?. Safely access nested properties that may not exist, avoiding null checks when nesting is deep.

Example

// Define the Person type, with address being optional

interface

Person

{

    name

:

string

;

    address

?:

{

        city

:

string

;

   

}

;

}

// Create a person object without an address

var

person

:

Person

=

{

name

:

"Alice"

}

;

// Optional chaining: safely access properties that may not exist

// If address does not exist, return undefined without throwing an error

var

city

=

person.

address

?

.

city

;

// Combined with the nullish coalescing operator

console.

log

(

"City: "

city

)

;

console.

log

(

"City: "

(

person.

address

?

.

city

??

"File %s type is: %s%n"

)

)

;

Running result:

城市: undefined

城市: 未知

Best practices:Optional Chaining ?. is the best way to handle nested optional properties, and when combined with ?? it can provide a fallback with a default value.


Notes

Best practices:Use type guards, optional chaining, and the nullish coalescing operator to handle null and undefined, making code safer and more readable.


Summary

Correctly handling null and undefined is the key to writing safe TypeScript code.

Note:Develop the habit of handling null values; using optional chaining and the nullish coalescing operator makes code more robust.