-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
'Never' is not checked for unreachability #10973
Comments
I raised this point in #9260 and @ahejlsberg responded in #9260 (comment) (see second half of comment). |
@yortus your example which @ahejlsberg commented on is slightly different then this case. That example is for inferred 'never' typing for functions. In my example I use a declared 'never' function. Just quoting @ahejlsberg :
Maybe inferred cases cannot reach 100%. I don't know. But for me, this example is 100%: function test1() {
let str: string;
fail();
str = 'helloworld'; // No error. Should error with unreachable code.
} Because it is nearly exactly the same as this one: function test1() {
let str: string;
throw new Error('oops');
str = 'helloworld'; // Error unreachable code detected
} This is also 100%: function test2() {
let str: string;
if (Math.random() > 0.5) {
str = 'helloworld';
}
else {
fail();
}
let str2 = str + ''; // Error: str is used before being assigned. But should not error.
} Because this one already are: function test2() {
let str: string;
if (Math.random() > 0.5) {
str = 'helloworld';
}
else {
throw new Error('oops');
}
let str2 = str + ''; // No error
} |
@tinganho First of all, I would prefer the behaviour you are suggesting here (i.e. detect the unreachable code and error). That aside, I don't think the compiler currently does any cross-function analysis, so it doesn't assume the code after calling |
To clarify what I said here, reachability analysis considers only the grammatical structure of the code, i.e. it doesn't factor in types. So, we know for certain that control won't reach a statement following a That said, I agree it would be nice if we could report reachability errors following calls to never-returning functions, be they implicitly or explicitly typed. However, it's not a trivial change given how the analysis is currently structured. Meanwhile, you can make it work by writing function fail(): never {
throw new Error('oops');
}
function test1() {
let str: string;
return fail();
str = 'helloworld'; // Error, unreachable code
}
function test2() {
let str: string;
if (Math.random() > 0.5) {
str = 'helloworld';
}
else {
return fail();
}
let str2 = str + ''; // Ok
} |
I think I'm starting to see a pattern here: |
The text was updated successfully, but these errors were encountered: