Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple type assertions in TypeScript

I was looking at the source code of an Angular repository and stumbled upon a line of code that uses multiple type assertions.

The code looks like this one, it uses 2 type assertion: unknown and Record<string, unknown>:

 (window as unknown as Record<string, unknown>)['ResizeObserver'] 

What does multiple assertions actually mean?

like image 260
The.Wolfgang.Grimmer Avatar asked Aug 27 '26 14:08

The.Wolfgang.Grimmer


1 Answers

You use type assertions too narrow down the type of a value so you can use it. This is known as double assertion.

The assertion from type S to T succeeds if either S is a subtype of T or T is a subtype of S.

Since we are unsure of the shape of the window object we cannot be sure that we can check that the ResizeObserver property has a value other than null.

So we can cast it to unknown, because anything can be assigned to unknown.

And because anything can be assigned to unknown we now have free range to shape the object how we want in order to satisfy our conditional. Since we need to check that a properties value is not null, we can simply use Record<string, unknown>

We end up with:

(window as unknown as Record<string, unknown>)['ResizeObserver'] != null

By doing this we can write a conditional to check that the ResizeObserver property is not null no matter what shape the window object has.

like image 160
about14sheep Avatar answered Aug 30 '26 07:08

about14sheep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!