Advanced Typescript. Type Guards and Differentiating Types

This article will demonstrate how you can check your types and instances using user-defined Type Guards and reserved keyword in Typescript in examples
Prerequisites
For our demo purposes, I’ll be using a simples TS project with two dev dependencies: typescript
and ts-node
(without any tsconfig
file).
package.json:

As you can see on a screenshot I’ve created an src/index.ts
file with a simple class.
I’m running *.ts
files using npx ts-node <file-path>
command.
And that’s it, that’s all you need. ✔️
Type Guards and Differentiating Types
For TS types differentiation we can use three different mechanisms:
typeof
keyword;instanceof
keyword;- user-defined
Type Guards
Let’s check how they work one-by-one.
1.1 Using “typeof” keyword
typeof
keyword is commonly used for checking value types likestring
,number
,bigint
,boolean
,function
,object
,symbol
andundefined
.
For describing how typeof
keyword works I’ve created a new file src/differentiation/typeof.ts
:
Let’s run this file and check that Typescript is ok with it:

1.2 Using "instanceof" keyword
instanceof
keyword is commonly used for differentiating Classes.
For describing how instanceof
keyword works I’ve created a new file src/differentiation/instanceof.ts
:
Let’s run this file and check that Typescript is ok with it:

1.3 Using user-defined Type Guards
Type Guards are mostly used for complex type checking.
You can define your custom Type Guard by using this code snippet:
function isSomeType(var): var is SomeType {...}
What does it mean? It’s basically means that isSomeType
function returns true
or false
, but… if it will return true
, than Typescript will be sure that var is SomeType
type.
Let’s look at how it works. For this example, I’ve created a new file src/differentiation/guards.ts
:
Run this file and check that Typescript is ok with it:

As you can see at line 47 we are setting valueClass.foo
(that could be either string
or a number
) to a number type variable someNumber
. And Typescript is ok with that because it knows that if isNumberClass()
function will return true — that means that valueClass
is a NumberClass
instance and foo
is definitely a number
.

!! Be aware of this kind of situation:
I have intentionally made a mistake in our example and now isNumberClass
function returns true for a StringClass
NOT a NumberClass

Typescript is NOT AWARE of your type-checking MISTAKES. It knows that
isNumberClass
function should return true ifinstance
isNumberClass
. But is it in reality Typescript doesn’t know.