TypeScript has is
operator which helps to create a test function for type checking. Recently I saw two different implementations of this operator, one of which uses asserts
keyword.
I didn't find information about the difference of the two ways of use in the docs. I played with it a little and if I'm correct, asserts
doesn't let you return anything from the function, but other than this I didn't find any differences.
Here is the code I tested with:
// 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
Question: Are there other differences between the two use cases?