-
Notifications
You must be signed in to change notification settings - Fork 12.2k
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
De-narrowing of never
with postfix !
#51097
Comments
Implementing this, some funny stuff happens. Let's say in the OP example you write type AorB = { kind: "A" } | { kind: "B" };
function fn(x: AorB) {
switch (x.kind) {
case "A":
console.log("It is A");
break;
case "B":
console.log("It is B");
break;
default:
const p = x!.kind; // <-- π
}
} What type should Naively, maybe What actually happens is that we fetch the symbol for The interesting thing about this is that the naive type Naturally (?) at that point you can write const p = x!.kind!; to get Are there other use cases for this? |
Implements microsoft#51097
This would make declare function what<T>(arg: T): void;
const x = null;
what(x!);
// ^?
what(x!!);
// ^? |
I suppose, though it would only be non-idempotent for values with a declared type of |
That would at least address the non-idempotency: in my example, function f(arg: number|string) {
if (typeof arg === 'number') {
} else if (typeof arg === 'string') {
} else {
console.error(`Unknown argument: ${arg!.toString()}`);
}
} Here, we un-narrow I wonder if rather than reusing |
This is strange, I don't like this idea of reverting never type. If you exclude all possibilities, you should not have any other type than "never". The access to an inferred "never" variable should always be like "(node as any).kind". |
1 similar comment
This is strange, I don't like this idea of reverting never type. If you exclude all possibilities, you should not have any other type than "never". The access to an inferred "never" variable should always be like "(node as any).kind". |
Thinking more about this, I'm very concerned with having the same operator both narrowing (the existing usage) and widening (i.e. de-narrowing). |
Seems like not much interest / use cases for this |
Suggestion
π Search Terms
never postfix narrowing unnarrowing
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
Postfix
!
, aka the non-null assertion operator, should be overloaded so that it can undo narrowings tonever
. Simply, when an expression of typenever
is the operand of!
, TypeScript should instead evaluate it as its declared type.π Motivating Example
Discriminator exhaustion
We should be able to use
!
to allow access to thekind
property:π» Use Cases
Feature detection - #51059
The text was updated successfully, but these errors were encountered: