Skip to content

Allow static assertions #18523

Closed
Closed
@dead-claudia

Description

@dead-claudia

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:

  1. Asserting a value's type statically without requiring an emit.
  2. Asserting the unreachability of a code path
  3. Verifying a complex data structure (like ESTree's) to avoid bugs.
  4. 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...

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions