镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Type assertion with as operator does not work on recursive functions #5403

Description

With --noImplicitAny:

function foo() {
    let element = foo() as number;
    return element;
}
/*
issue5403.ts(1,10): error TS7023: 'foo' implicitly has return type 'any' because it does not
have a return type annotation and is referenced directly or indirectly in one of its return
expressions.
issue5403.ts(2,6): error TS7022: 'element' implicitly has type 'any' because it does not have
a type annotation and is referenced directly or indirectly in its own initializer.
*/

Activity

  1. mhegazy commented on Oct 26, 2015

    @mhegazy
    Contributor

    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.

    you can find more information in #1146 (comment)

  2. saschanaz commented on Oct 26, 2015

    @saschanaz
    ContributorAuthor

    Mohamed Hegazy (@mhegazy) Here it has as number type assertion so the type of element should be explicitly number.

  3. mhegazy commented on Oct 26, 2015

    @mhegazy
    Contributor

    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" as number // 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.

  4. saschanaz commented on Oct 26, 2015

    @saschanaz
    ContributorAuthor

    Ah, I see. Thanks for your explanation. 👍

  5. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions