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
问题:这两种用例之间还有其他的差异吗?