Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

as any as customeType

I was studying the the latest angular code which is in typescript and came to the following line:

const scope = self as any as ServiceWorkerGlobalScope;

What I don't understand about above is: if the type self is any why would you cast it as ServiceWorkerGlobalScope? Why wouldn't you just declare it as ServiceWorkerGlobalScope like the following:

const scope = self as ServiceWorkerGlobalScope;

or

const scope : ServiceWorkerGlobalScope = self;

What does that line mean? Does it mean scope is of type any which most like to be of type ServiceWorkerGlobalScope?

like image 747
MHOOS Avatar asked Oct 27 '25 10:10

MHOOS


1 Answers

If you use the simplified:

const scope : ServiceWorkerGlobalScope = self;

TypeScript will check the strucutre of self against the type ServiceWorkerGlobalScope. If it finds the types to be incompatible you'll receive an error along the lines of:

Type 'Window' cannot be converted to type 'ServiceWorkerGlobalScope'. Property '...' is missing in type 'Window'.

By moving self into the any type first, the check is then performed between the any type and the ServiceWorkerGlobalScope type. In this case, any is compatible with "any" other type and there are no warnings.

This is the same flow that applies to type assertions, you can attempt a type assertion:

x = <ServiceWorkerGlobalScope>y

But a type assertion still performs type checking. If you want to "opt out" of type checking, you use the any type as an intermediary:

x = <ServiceWorkerGlobalScope><any>y
like image 158
Fenton Avatar answered Oct 29 '25 01:10

Fenton



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!