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
Type assertion with as operator does not work on recursive functions #5403
functionfoo(){letelement=foo()asnumber;returnelement;}/*issue5403.ts(1,10): error TS7023: 'foo' implicitly has return type 'any' because it does nothave a return type annotation and is referenced directly or indirectly in one of its returnexpressions.issue5403.ts(2,6): error TS7022: 'element' implicitly has type 'any' because it does not havea type annotation and is referenced directly or indirectly in its own initializer.*/
The compiler uses right hand expressions to infer the type of un-annotated declarations. it also uses return expressions to infer the type of function declarations without return type annotations.
In the example above, the compiler tries to figure out the type of element, and as part of doing this it figures it needs to find the return type of foo, which is the type of element. the compiler breaks these cycles by giving them the type any. the warning tells you that this happened.
either give the function a return type annotation, or declare element as number.
this is a type assertion and not a type annotation. the type assertion needs to be checked that it is assignable to the expression. for instance:
"string"asnumber// error Neither type number nor type string are assignable to each other
so the compiler needs to do this check, but to do it, it needs to know the type of foo() which is the type of element, which it was trying to figure its type already.
Activity
mhegazy commentedon Oct 26, 2015
The compiler uses right hand expressions to infer the type of un-annotated declarations. it also uses return expressions to infer the type of function declarations without return type annotations.
In the example above, the compiler tries to figure out the type of
element, and as part of doing this it figures it needs to find the return type offoo, which is the type ofelement. the compiler breaks these cycles by giving them the typeany. the warning tells you that this happened.either give the function a return type annotation, or declare element as number.
you can find more information in #1146 (comment)
saschanaz commentedon Oct 26, 2015
Mohamed Hegazy (@mhegazy) Here it has
as numbertype assertion so the type ofelementshould be explicitlynumber.mhegazy commentedon Oct 26, 2015
this is a type assertion and not a type annotation. the type assertion needs to be checked that it is assignable to the expression. for instance:
so the compiler needs to do this check, but to do it, it needs to know the type of
foo()which is the type ofelement, which it was trying to figure its type already.saschanaz commentedon Oct 26, 2015
Ah, I see. Thanks for your explanation. 👍