-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow static assertions #18523
Comments
Looks pretty much the same as #10421, but the syntax proposed there uses |
I've been using type HasType<T, Q extends T> = Q; Example: type Just<T> = { tag: 'just', value: T }
type Nothing = { tag: 'nothing' }
type Maybe<T> = Just<T> | Nothing
function f<T>(x: Maybe<T>) {
switch (x.tag) {
case 'just': {
type StaticAssert = HasType<Just<T>, typeof x>
return 0;
}
case 'nothing': {
type StaticAssert = HasType<Nothing, typeof x>
return 1;
}
default: {
type StaticAssert = HasType<never, typeof x>
// false positive, however it's usually not a problem
type FalsePositive = HasType<number, typeof x>
throw 'never?';
}
}
} |
@yortus That issue involves a type-casting component (it calls itself type narrowing, but it's not really). Mine is simply a type assertion, and a relatively dumb one at that. In particular, these two would be technically equivalent mod emit (for mine): // Proposed
assert Foo extends Bar;
assert foo is Bar;
// Equivalent
const _unused1: Bar = 0 as any as Foo;
const _unused2: Bar = 0 as any as typeof foo; |
Tracking at #10421 |
To be clear we're interested in both the "function call with type-asserting side effects" and "statement-form type assertion that affects the rest of the block" forms. |
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
:My proposal:
These are all statements, and none of these would cause an emit. (You could include comments, though.)
This would be equally useful in:
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...
The text was updated successfully, but these errors were encountered: