Closed
Description
Currently, there's only a few ways to statically assert a type (and error if it fails), and they're extremely hacky and limited to effectively value is Type
:
// 1.
const expectType: T = something;
const expectUnreachable: never = something;
// 2.
function expectType<T>(value: T): void {}
expectType<T>(something);
expectType<never>(something); // unreachable
My proposal:
// Type-level, error iff `Foo` is not assignable to `Bar`
assert Foo extends Bar;
// Type level, error if it is reachable
assert never;
// Value-level sugar
assert foo is Foo;
assert typeof foo extends Bar; // equivalent
These are all statements, and none of these would cause an emit. (You could include comments, though.)
This would be equally useful in:
- Asserting a value's type statically without requiring an emit.
- Asserting the unreachability of a code path
- Verifying a complex data structure (like ESTree's) to avoid bugs.
- Giving first-class support for testing external definition files like those on DefinitelyTyped.
And in case you're wondering, I drew quite a bit of inspiration from C/C++.
I know this general idea has been brought up multiple before, but there oddly was no dupe I could immediately find...