TypeScript Type Guards
Type Guards are a very important type-narrowing mechanism in TypeScript.
It allows developers to use specific conditional checks at runtime so that the TypeScript compiler can accurately infer the concrete type of a variable.
With type guards, we can safely access properties and methods of a specific type within a union-type variable.
Why Type Guards Are Needed
In TypeScript, a variable may be declared as a union of multiple types.
When we need to perform different operations based on different types, the compiler cannot automatically determine the current concrete type.
Type guards are the key mechanism for solving this problem.
Concept explanation:The core principle of type guards is "type narrowing" (Type Narrowing). Through conditional checks, TypeScript automatically narrows a union type to a concrete type.
typeof Type Guards
typeof is the most commonly used type guard, used to check primitive types (string, number, boolean, etc.).
It returns a string indicating the type of the value.
Basic typeof Usage
// Define a function that takes a union type
// The parameter value may be a string or a number
function
printValue
(
value
:
string
|
number
)
:
void
{
// Use typeof to check the type
// When the if condition is true, TypeScript automatically narrows value to the string type
if
(
typeof
value
===
"string"
)
{
// At this point, TypeScript knows value is a string
// The string's length property can be safely accessed
console.
log
(
"String length: "
value.
length
)
;
}
else
{
// When entering the else branch, TypeScript knows value is not a string
// It can only be the number type
// Mathematical operations can be safely performed
console.
log
(
"Number doubled: "
(
value
2
)
)
;
}
}
// Test call
printValue
(
"hello"
)
;
// Pass in a string
printValue
(
42
)
;
// Pass in a number
Running result:
字符串长度: 5
数字翻倍: 84
Types supported by typeof:
- "string" - String type
- "number" - Number type (including NaN and Infinity)
- "boolean" - Boolean type
- "undefined" - Undefined type
- "object" - Object type (note: arrays and null are also identified as "object")
- "function" - Function type
Note:typeof returns "object" for both arrays and null. If you need to precisely distinguish arrays from objects, you need to use other methods.
instanceof Type Guards
instanceof is used to check whether an object is an instance of a certain class.
It determines the type by checking the object's prototype chain.
Basic instanceof Usage
// Define a Dog class
class
Dog
{
// The dog's bark method
bark
(
)
:
void
{
console.
log
(
"Woof woof woof!"
)
;
}
}
// Define a Cat class
class
Cat
{
// The cat's meow method
meow
(
)
:
void
{
console.
log
(
"Meow meow meow!"
)
;
}
}
// A function that takes a union type
function
makeSound
(
animal
:
Dog
|
Cat
)
:
void
{
// Use instanceof to check whether animal is a Dog or a Cat
// When the if condition is true, TypeScript narrows animal to the Dog type
if
(
animal
instanceof
Dog
)
{
// Dog-specific methods can now be called
animal.
bark
(
)
;
}
else
{
// In the else branch, TypeScript narrows animal to the Cat type
animal.
meow
(
)
;
}
}
// Test call
makeSound
(
new
Dog
(
)
)
;
// Create a Dog instance and call it
makeSound
(
new
Cat
(
)
)
;
// Create a Cat instance and call it
Running result:
汪汪汪!
喵喵喵!
Explanation:
instanceof checks an object's prototype chain, so it can only be used with class instances, not with interfaces or type aliases.
Custom Type Guards
When the built-in typeof and instanceof cannot meet your needs, you can create custom type guard functions.
Custom type guards use the value is Type return type syntax.
Custom Guard Functions
// Define a custom type guard function
// The return type uses the "value is Type" format
// This tells TypeScript: when the function returns true, the parameter type is string
function
isString
(
value
:
any
)
:
value is string
{
// Use typeof to check whether it is a string
return
typeof
value
===
"string"
;
}
// Another custom guard: check whether it is a number
function
isNumber
(
value
:
any
)
:
value is number
{
return
typeof
value
===
"number"
;
}
// Define an array type guard
function
isArray
(
value
:
any
)
:
value is any
[
]
{
return
Array
.
isArray
(
value
)
;
}
// A function that processes the value
function
processValue
(
value
:
string
|
number
|
any
[
]
)
:
void
{
// Use a custom guard for type checking
if
(
isString
(
value
)
)
{
// TypeScript knows that value is a string
// The toUpperCase() method can be called
console.
log
(
"String to uppercase: "
value.
toUpperCase
(
)
)
;
}
else
if
(
isNumber
(
value
)
)
{
// TypeScript knows value is the number type
// The toFixed() method can be called
console.
log
(
"Number formatted: "
value.
toFixed
(
2
)
)
;
}
else
if
(
isArray
(
value
)
)
{
// TypeScript knows value is the array type
console.
log
(
"Array length: "
value.
length
)
;
}
}
// Test call
processValue
(
"hello"
)
;
processValue
(
3.14159
)
;
processValue
(
[
1
,
2
,
3
,
4
,
5
]
)
;
Running result:
字符串转大写: HELLO
数字格式化: 3.14
数组长度: 5
Tip:The key to a custom type guard is the return type
value is Type, which is the marker TypeScript uses to recognize a type guard.
in Operator Type Guards
The in operator can check whether an object contains a certain property.
When in is used in a condition, TypeScript automatically narrows the object's type range.
in Operator Usage
// Define two interfaces with different properties
interface
A
{
a
:
string
;
// Has only property a
}
interface
B
{
b
:
number
;
// Has only property b
}
// A function that takes a union type
function
process
(
obj
:
A
|
B
)
:
void
{
// Use in to check whether the object contains property "a"
if
(
"a"
in
obj
)
{
// In the if branch, TypeScript knows obj contains property a
// Therefore obj's type is narrowed to A
console.
log
(
"A's property a: "
obj.
a
)
;
}
else
{
// In the else branch, obj does not contain property a
// TypeScript knows obj can only be of type B
// Therefore property b can be safely accessed
console.
log
(
"B's property b: "
obj.
b
)
;
}
}
// Test call
process
(
{
a
:
"hello"
}
)
;
// Pass in an object containing property a
process
(
{
b
:
42
}
)
;
// Pass in an object containing property b
Running result:
A 的属性 a: hello
B 的属性 b: 42
Discriminated Unions and Type Guards
A discriminated union is a powerful pattern that distinguishes union type members through a common "discriminant" property.
Combined with switch statements or if checks, complete type guards can be achieved.
Implementing a Calculator with a Discriminated Union
// Define a Circle interface, using the kind property as the discriminant
interface
Circle
{
kind
:
"circle"
;
// Discriminant field: value is "circle"
radius
:
number
;
// Radius
}
// Define a Rectangle interface
interface
Rectangle
{
kind
:
"rectangle"
;
// Discriminant field: value is "rectangle"
width
:
number
;
// width
height
:
number
;
// height
}
// Define a Triangle interface
interface
Triangle
{
kind
:
"triangle"
;
// Discriminant field: value is "triangle"
base
:
number
;
// Base
height
:
number
;
// height
}
// Define a union type
type Shape
=
Circle
|
Rectangle
|
Triangle
;
// A function that calculates area
function
getArea
(
shape
:
Shape
)
:
number
{
// Use a switch statement for type guarding
// Based on the value of the kind property, TypeScript automatically narrows the type
switch
(
shape.
kind
)
{
case
"circle"
:
// shape is narrowed to the Circle type
// The radius property can be accessed
return
Math
.
PI
shape.
radius
**
2
;
case
"rectangle"
:
// shape is narrowed to the Rectangle type
// The width and height properties can be accessed
return
shape.
width
shape.
height
;
case
"triangle"
:
// shape is narrowed to the Triangle type
return
0.5
shape.
base
shape.
height
;
}
}
// Test call
var
circle
=
{
kind
:
"circle"
as
const
,
radius
:
5
}
;
var
rectangle
=
{
kind
:
"rectangle"
as
const
,
width
:
4
,
height
:
6
}
;
var
triangle
=
{
kind
:
"triangle"
as
const
,
base
:
3
,
height
:
4
}
;
console.
log
(
"Circle area: "
getArea
(
circle
)
.
toFixed
(
2
)
)
;
console.
log
(
"Rectangle area: "
getArea
(
rectangle
)
)
;
console.
log
(
"Triangle area: "
getArea
(
triangle
)
)
;
Running result:
圆形面积: 78.54
矩形面积: 24
三角形面积: 6
Explanation:Discriminated unions are one of the most recommended patterns in TypeScript. They distinguish different type members through a common literal property (usually kind or type), making the code both type-safe and easy to maintain.
null and undefined Checks
When handling values that may be null or undefined, a direct equality check is also an effective type guard.
null Check
// Define a function parameter that may be null
function
getLength
(
str
:
string
|
null
)
:
number
{
// Directly check that str is not equal to null
// When the condition is true, TypeScript knows str is not null
// At this point, str's properties can be safely accessed
if
(
str
!==
null
)
{
return
str.
length
;
}
// Handling the null case
return
0
;
}
// Test call
console.
log
(
getLength
(
"hello"
)
)
;
// A normal string
console.
log
(
getLength
(
null
)
)
;
// Pass in null
Running result:
5
0
Tip:After enabling strictNullChecks, it is recommended to always perform null checks. You can use optional chaining (?.) and nullish coalescing (??) to simplify code.
Truthiness Narrowing
In addition to explicit type checks, TypeScript also narrows type ranges through truthiness assertions (Truthiness).
Truthiness Narrowing
// A string that may be undefined
function
greet
(
name
?:
string
)
:
string
{
// Use the short-circuit operator: if name is undefined or an empty string, use the default value
// In the code block after &&, TypeScript knows name must have a value
return
name
&&
"Hello, "
name
;
}
// Test
console.
log
(
greet
(
"RUNOOB"
)
)
;
console.
log
(
greet
(
)
)
;
Running result:
Hello, RUNOOB
Hello, undefined
Notes
- **Type guards must be used in conditional branches:** TypeScript only narrows types after a type guard has been used for a conditional check
- **The return type must be a type predicate:** The return type of a custom type guard must be
value is TypeFormat - **Discriminated unions are best practice:** For complex union types, it is recommended to use the discriminated union pattern
- **Note the completeness of type narrowing:** When using a switch statement, it is recommended to handle all possible cases
Note:When working with union types, prefer the discriminated union pattern. It not only makes the code clearer but also fully leverages TypeScript's type inference capabilities.
Summary
Type guards are an important part of the TypeScript type system.
- **typeof:** The most common approach, suitable for checking primitive types
- **instanceof:** Checks whether an object is an instance of a specific class
- **Custom guards:** Through
value is Typesyntax to implement flexible type checking - **in:** Checks whether an object contains a specific property
- **Discriminated unions:** The recommended best-practice pattern, distinguishing types through a discriminant field
- **Truthiness narrowing:** Type narrowing using JavaScript's truthiness evaluation