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
{{ message }}
Repository navigation
TS does not automatically understand object with accessor type if not extracted to a variableΒ #46111
typeT_Object={theKey: string;};typeT_MyType=T_Object|string;functionisItObject(input: T_MyType): input is T_Object{return!!(inputasT_Object).theKey;}constmyVariable: {[key: string]: T_MyType}=//@ts-ignoresomehowGetSomething();functionmyFunctionWithError(key: string){if(isItObject(myVariable[key])){console.log('it is object');returnmyVariable[key].theKey;}returnmyVariable[key];}functionmyValidFunction(key: string){constextractedVariable=myVariable[key];if(isItObject(extractedVariable)){console.log('it is object');returnextractedVariable.theKey;}returnmyVariable[key];}
π Actual behavior
There are two functions at the bottom of the code. The only difference is that in second case, I extracted myVariable[key] to a variable and used that in if condition and return value. In first function it gives me error, but in the second one (extracted variable) it doesn't.
π Expected behavior
I expected TypeScript to automatically infer myVariable[key] is an object inside the if condition with isItObject(myVariable[key])
However is it safe to do this case if myVariable[key] might not return same value between calls?
With intermediate constant you can be sure that constant isn't changed between if and usage but not with property access.
Activity
IllusionMH commentedon Sep 28, 2021
Looks like duplicate of #44899 which considered duplicate of #10530 (that accumulated a lot of different cases in comments e.g. #10530 (comment))
a-tarasyuk commentedon Sep 28, 2021
I think this PR #45974 handles this case. Playground
aghArdeshir commentedon Sep 28, 2021
Yes Oleksandr Tarasiuk (@a-tarasyuk) . That would cover this case. Nice π
aghArdeshir commentedon Sep 28, 2021
Yes Andrii Dieiev (@IllusionMH) those two iseues seem like to be a better way of expressing what I wanted. Thanks. π
I think this issue can/should be closed.
IllusionMH commentedon Sep 28, 2021
Oleksandr Tarasiuk (@a-tarasyuk) great work as always!
However is it safe to do this case if
myVariable[key]might not return same value between calls?With intermediate constant you can be sure that constant isn't changed between
ifand usage but not with property access.typescript-bot commentedon Oct 1, 2021
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.