How to fix typescript types in Service Worker?

Asked

Viewed 57 times

0

I have a Typescript file that will be used in Service Worker, but by default, the scope/context/this global and variable self file will always reference to Window type, which is not what happens at runtime:

// [...]

self.clients.matchAll()

// [...]

Property 'clients' does not exist on type 'Window' . ts(2339)

How to set this issue during build not to occur and the IDE shows the right suggestions when typing self.<qualquer coisa>?

1 answer

-1

You need to declare the type of the variable this, just as you declare the types of arguments.

For example:

function onclickHandler(this: HTMLInputElement) {
    // como "this" é um input, aqui eu posso acessar a propriedade "value"
    console.log(this.value)
}

Notice that this is not the first argument of the function, this is just the syntax that TS uses to declare the type of the this, actually this function is not expecting any argument.

As can be seen in the following code:

function recebeParametros(this: any, arg1: boolean, arg2: number, arg3: string[]) {
    console.log(arg1, arg2, arg3)
}

recebeParametros(
    true, 
    10, 
    ['a', 'b', 'c']
)

I never pass the value of this for the function. When this function is transcompeted to JS the this disappears from the declaration, it exists only in the TS to indicate the type of this.

  • I do not mean a value received in some function, but rather the this global, out of functions, classes, objects and other scopes. This this in the client is the object window, but within a Service Worker it is not that object but one of the type ServiceWorkerGlobalScope (if I’m not mistaken). If I do not configure anything there is no way Typescript knows that this particular file is a Service Worker and then it assumes it is a Window, causing build error and in the IDE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.