microsoft / microsoft/TypeScript

Type inference only works on the same line as the variable declaration

Abierto
#41,289 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

In Discussion Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

I ran into this odd behavior while writing some tests, that do the typical describe, declare a closure-scope variable, and in beforeEach, assign some object to that variable that is used in each of the tests inside.

Search Terms:
infer, inference, closure, scope, broken, any, cast

Initially, I thought it was limited to closure scope, but I then started reducing the reproduction sample more and more, and realized, it's broken even if it's on the very next line:

Code

// given
interface Foo {
    id: string;
}

function make(): Foo {
    return {
        id: 'akatechis',
    }
}

// u1 is correctly inferred to be of type Foo.
let u1 = make();

// u2 is incorrectly inferred to be of type any.
let u2;
u2 = make();

// this was the scenario in which I originally ran into this:
// a closure scoped variable that is assigned in an inner function
function outer () {
    // u3 is inferred to be of type any
    let u3;
    return {
        inner() {
            // u3 here is still any
            u3 = make();

            // surprisingly, returning u3 here causes the return type of inner() to be Foo, not any???
            return u3;
        }
    }
}

Expected type declarations:

interface Foo {
    id: string;
}
declare function make(): Foo;
declare let u1: Foo;
declare let u2: Foo; // <---- this should have been inferred to be Foo
declare function outer(): {
    inner(): Foo;
};

Actual type declarations:

interface Foo {
    id: string;
}
declare function make(): Foo;
declare let u1: Foo;
declare let u2: any;
declare function outer(): {
    inner(): Foo;
};

Playground Link: playground

Related Issues:
The only thing that I found somewhat close to this issue was the question in the FAQ about unused generic types causing type widening, but I don't think this is it, because I'm not using generics here.

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza con la reproducción vinculada en TypeScript Playground y compara las declaraciones inferidas para u1, u2 y outer(). Lee la entrada relacionada de las FAQ sobre type widening para descartar esa explicación y, después, identifica el comportamiento de inferencia de tipos responsable de la discrepancia. Se considera terminado cuando u2 se infiere como Foo, conservando el resultado mostrado de outer().

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
typescript
Área
compilers
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bien especificado
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.