Skip to content

Fails for simple type inference #32586

Closed
Closed
@kgtkr

Description

@kgtkr

TypeScript Version: 3.6.0-dev.20190726

Search Terms:
type inference

Code

declare function f(x: string | undefined): string;
declare function id<T>(x: T): T;

let state: undefined | string = undefined;
while (true) {
  const x = id(f(state));
  state = x;
}
// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.

Expected behavior:
x: string

Actual behavior:
'x' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

Playground Link:
https://www.typescriptlang.org/play/#code/CYUwxgNghgTiAEAzArgOzAFwJYHtVIAoAPALngGcMYtUBzeAH3jVERpGAEozLq6BuAFChIsBCnTY88LMAA8AFQB8xMgu7wFQwRBAYKGKBhBkWINqg6MDfegF5mqVu2BCA7gAssu+ASrIQTngAb0F4eDA8SngieAdZAkQCSiNAziFwlOM4mKEAX0EgA

Related Issues:

Activity

ahejlsberg

ahejlsberg commented on Jul 28, 2019

@ahejlsberg
Member

This is a design limitation in the control flow analyzer. Ideally the analyzer would realize that id(f(state)) always has type string regardless of the type of state. However, the analyzer attempts to resolve the type of the expression, which entails resolving the type of state, which entails resolving the type of x (because of the state = x assignment and the back edge of the loop), which leads to a circularity and therefore an implicit any.

added
Design LimitationConstraints of the existing architecture prevent this from being fixed
on Jul 28, 2019
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

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ahejlsberg@RyanCavanaugh@kgtkr

        Issue actions

          Fails for simple type inference · Issue #32586 · microsoft/TypeScript