You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function testOne(foo: string | undefined) {
const thing = !!foo;
if(thing) {
// Foo type is String
return foo.charAt(0);
}
return 'undefined'
}
function testTwo(foo: string | undefined) {
const thing: boolean = !!foo;
if(thing) {
// Foo type is string | undefined
return foo.charAt(0);
}
return 'undefined'
}
π Actual behavior
foo is typed as string | undefined if thing has explicit type of boolean
π Expected behavior
foo should be typed as string if thing has type of boolean just like if thing's type is inferred
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered:
jauwesome
changed the title
Adding boolean type assertion changes type narrowing for undefined
Adding boolean type assertion changes type narrowing
Oct 10, 2024
@RyanCavanaugh Thanks for the quick response! Is there a specific reason why this choice was made? I don't see that listed. Regardless we can close the ticket.
IIRC it's possible to get into a type resolution circularity with this inference in a way that wouldn't really be solvable, so you need some "out" in cases where you're not using it for narrowing purposes
π Search Terms
Type Narrowing
Boolean
Undefined
π Version & Regression Information
Version: 5.6.3
Regression: Unknown
β― Playground Link
https://www.typescriptlang.org/play/?noUnusedLocals=true&noUnusedParameters=true#code/GYVwdgxgLglg9mABFApgZygeTCgFMOOALkQwCcYwBzRAH0XABMVhKVGBKRAbwChEBiCAgzIAFpRoBeRAEJZBOAG5+gmMFxQJ1Ln0H7EZFFBBkkigHQQxAQzIBBKLgAMHFfoC+qgUZNnEAORMLGyMAbxevKCQsAjI6FAAKgDucPiEJOSSdAxgzKw4nDzeQiJQ4pIkAEaEADYoNkgy8oruahpakrol+r6m5oRWtg5Orm0CXr3G-YHBBezhHkA
π» Code
π Actual behavior
foo
is typed asstring | undefined
ifthing
has explicit type ofboolean
π Expected behavior
foo
should be typed asstring
ifthing
has type ofboolean
just like ifthing
's type is inferredAdditional information about the issue
No response
The text was updated successfully, but these errors were encountered: