Typescript 3.7 adds assertions in control flow analysis.
An
asserts
return type predicate indicates that the function returns only when the assertion holds and otherwise throws an exception
Hacks on consumer side are not needed anymore.
interface Foo { bar(): void }
declare function getFoo(): Foo | undefined;
function assert(value: unknown): asserts value {
if (value === undefined) {
throw new Error('value must be defined');
}
}
function test() {
const foo = getFoo();
// foo is Foo | undefined here
assert(foo);
// foo narrowed to Foo
foo.bar();
}
Additionally one can assert that provided parameter is of required type:
declare function assertIsArrayOfStrings(obj: unknown): asserts obj is string[];
function foo(x: unknown) {
assertIsArrayOfStrings(x);
return x[0].length; // x has type string[] here
}