Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fails for simple type inference #32586

Closed
kgtkr opened this issue Jul 27, 2019 · 1 comment
Closed

Fails for simple type inference #32586

kgtkr opened this issue Jul 27, 2019 · 1 comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@kgtkr
Copy link

kgtkr commented Jul 27, 2019

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:

@ahejlsberg
Copy link
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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants