【发布时间】:2023-02-18 15:25:23
【问题描述】:
TypeScript 具有 is 运算符,可帮助创建用于类型检查的测试函数。最近我看到了这个运算符的两种不同实现,其中一种使用了asserts关键字。
我没有在文档中找到有关两种使用方式差异的信息。我试了一下,如果我是对的,asserts 不会让你从函数返回任何东西,但除此之外我没有发现任何区别。
这是我测试过的代码:
// Asserts and tests the value without returninng anything
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") throw Error("value is not a string");
}
// Tests the value and returns something so it can be used for typecheck
// more explicitly
function testIsString(value: unknown): value is string {
return typeof value === "string";
}
const string = "hello";
const number = 123;
assertIsString(string); // does nothing
assertIsString(number); // throws Error
testIsString(string); // returns true
testIsString(number); // returns false
问题:这两个用例之间还有其他区别吗?
【问题讨论】:
标签: javascript typescript types assertion typechecking