typescriptassertionwebcrypto-apitypeguards

Assert type of global using TypeScript assertion function?


Is it possible to create a TypeScript assertion function that asserts the type of something other than the arguments passed to it – a global, for instance:

// Pseudo-code
function assertIsSubtleCryptoSupported(
): asserts globalThis.crypto.subtle is InstanceType<SubtleCrypto> {
  if (globalThis.crypto?.subtle === undefined) {
    throw new Error('...');
  }
}

globalThis.crypto.subtle; // Type error
assertIsSubtleCryptoSupported();
globalThis.crypto.subtle; // OK

Solution

  • Assertion functions and type guards can only affect their arguments.

    Alternatively, you could write an assertion function and pass global to it to infer its properties:

    function assert(arg: unknown): asserts arg is {crypto: {subtle2: 'str'}} {}
    

    Testing:

    assert(global);
    
    global.crypto.subtle2 // 'str'