WebExt Core
Proxy Service

Service Keys

There are two ways of defining service keys:

  1. Using a string literal: This is simple, but it provides no type-safety guaranteeing that the registered service is the same type as the proxy. Notice how you have to provide a type argument to the createProxyService function.
    const key = 'math-service';
    registerService(key, new MathService());
    const proxy = createProxyService<MathService>(key);
    
  2. Cast to ProxyServiceKey: The key is cast to a "branded type" that contains the service type. This guarantees you both register the expected service and create a proxy with the correct type with minimal code.
    import type { ProxyServiceKey } from '@webext-core/proxy-service';
    
    const key = 'math-service' as ProxyServiceKey<MathService>;
    registerService(key, new MathService());
    const proxy = createProxyService(key);
    

Using ProxyServiceKey is highly recommended. It ensures type-safety everywhere, and it usually a good idea to create a shared constant for keys like this, so just add a simple cast!

Just make sure wherever your store the service keys, you DO NOT IMPORT THE REAL SERVICES, just their types:

proxy-service-keys.ts
import type { ProxyServiceKey } from '@webext-core/proxy-service';
import type { MathService } from './math-service';
//     ^^^^ DO NOT FORGET THE type KEYWORD

export const MATH_SERVICE_KEY = 'math-service' as ProxyServiceKey<MathService>;