使用TypeScript的断言函数来断言全局变量的类型?

huangapple go评论61阅读模式
英文:

Assert type of global using TypeScript assertion function?

问题

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

globalThis.crypto.subtle; // 类型错误
assertIsSubtleCryptoSupported();
globalThis.crypto.subtle; // 正常
英文:

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&lt;SubtleCrypto&gt; {
  if (globalThis.crypto?.subtle === undefined) {
    throw new Error(&#39;...&#39;);
  }
}

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

答案1

得分: 1

断言函数类型守卫 只能影响它们的参数。

或者,您可以编写一个断言函数,并将 global 传递给它以推断其属性:

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

测试:

assert(global);

global.crypto.subtle2 // 'str'
英文:

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: &#39;str&#39;}} {}

Testing:

assert(global);

global.crypto.subtle2 // &#39;str&#39;

huangapple
  • 本文由 发表于 2023年7月11日 06:05:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定