0

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
5
  • 1
    Does this work? function assert(global: unknown): asserts global is {crypto: {subtle: type}} {} and using assert(global) Commented Jul 10, 2023 at 22:14
  • My understanding is along the lines of @wonderflame's. It's definitely possible (through property access) to assert something about a global, though. Commented Jul 10, 2023 at 23:01
  • 2
    The answer to the question is: no, an assertion function can only affect the apparent type of one of its arguments... or it can affect the apparent type of the object on which it's called (that is, an assertion method returning asserts this is ⋯). There's no facility to affect other values in other scopes. Does that fully address the question? If so I could write up an answer explaining; if not, what am I missing? Commented Jul 11, 2023 at 0:44
  • I think that you're technically correct @jcalz (the best kind of correct). Commented Jul 11, 2023 at 18:09
  • @wonderflame's answer is a good alternative. You should both write up your answers! typescriptlang.org/play?jsx=0&module=6#code/… Commented Jul 11, 2023 at 18:09

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.