英文:
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<SubtleCrypto> {
if (globalThis.crypto?.subtle === undefined) {
throw new Error('...');
}
}
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: 'str'}} {}
Testing:
assert(global);
global.crypto.subtle2 // 'str'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论