microsoft / microsoft/TypeScript

Inferred type for accumulator and return value of `Array#reduce` is incorrect when used with `Record<string, unknown>`

Abierto
#59,196 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Domain: check: Type Inference Help Wanted Possible Improvement
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

🔎 Search Terms

"array reduce unknown"

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Array#reduce
⏯ Playground Link

https://www.typescriptlang.org/play/?#code/PQKhCgAIUglBTAJgVwMYEsB2BzSBDTfAJyLwE9IB7AM0iPlUqMQGdIB3dAFwAtIWuRLLgBueADbJ4LKCGDhMeALbSADnlTxIAUQAey1ePgBBSAG8okK40wDipCgF5IAbQC6+NgkbMAPAKEcABp+QWEAPndLa0pbLjokNCRIZzwScgA6ehRNAApcjVQAShTw-FRUELMAX084BiZEfzDgyExkJQAjeCJwovBohJzk4GBIABUyVS10Nh96VHjc70bmwOwQ9q6evvBqgdAIaEgAZWUtPDY9AyNTeF1NVXjOXnxCNIcqWgXGthe+ZCYADWmEo7EIYkk0lk8kUKhY6k0On0SkM8AAQuZBjY7B9yClXB5LvUfE0AsIQoCQWDMJE3NjYnZsklEAS8WQsok8gUKiVHGVClVasSVn5ya0tt1ev1BszNKzRhMpjM2AA5ADy40g8wYSxYPEoyHErO6JNW4o2bQ6Ut2+3Ah1kp3OdWuqKMmPuj3ihQ6RrwXCYkFm2su8QDbyonQAVrrIFxlRxuHwCEHMIh7vx0NhFFxkPRUwJ4HhWTQEqSYQpzgiNFpXWiAMJYqwxOL2fHOdx1UVklqWqmg8F0hmtuXJVLpDmj-KFPkCipCupmVxA+BkABcoXWbg3kp6kGqMubQxZkEVk2mQbVmu1TAWeoNRpNWiXLhX683wm3Vu2RH3-TtDrHGcKguiiaIeg88BPImrwpuyXwRpQ0axvGF7-BGWDprombZv6eYzHERYlt8DTMBWcJqDWyI3PAAAiTbNji3oTgSnbEi+b4bhaX79jS+5REeTHHvKbITpywzTrypTlJU5jCl4pE9usmzWjsh7NqOCpjOeKqQBqWo6oskC5PqhrGpAprdmsFLfja-4HGAjrARcVxge6kCelB3oVL64j+oGwaoKGcaUPgtl7lghbFghPxkdAsJVoitZuRiDEtriLEdkSCmktZrS8YOAmMYy8SaaJDjiUkknFNJgpyXUu5EOpVhlWeCaBbesa5I19lAA

💻 Code
/**
 * Reducing an array of records with string values
 */
namespace ExampleA {
    const array = [] as Record<string, string>[]
    const reduced = array.reduce((acc) => acc, {} as Record<string, number>)

    reduced // Type is correct (Record<string, number>)
}

/**
 * Same as ExampleA except with an array of records with unknown values
 */
namespace ExampleB {
    const array = [] as Record<string, unknown>[]
    const reduced = array.reduce((acc) => acc, {} as Record<string, number>)

    reduced // Type is NOT correct (should be Record<string, number>)
}

/**
 * Same as ExampleB except accumulator is cast to an object type with an index signature instead of record
 */
namespace ExampleC {
    const array = [] as Record<string, unknown>[]
    const reduced = array.reduce((acc) => acc, {} as { [key: string]: number })

    reduced // Type is NOT correct (should be { [key: string]: number })
}

/**
 * Same as ExampleB except with an array of an object type with an index signature instead of record
 */
namespace ExampleD {
    const array = [] as { [key: string]: unknown }[]
    const reduced = array.reduce((acc) => acc, {} as Record<string, number>)

    reduced // Type is NOT correct (should be Record<string, number>)
}

/**
 * Same as ExampleB except accumulator is cast to a number instead of record
 */
namespace ExampleB {
    const array = [] as Record<string, unknown>[]
    const reduced = array.reduce((acc) => acc, {} as number)

    reduced // Type is correct (number)
}
🙁 Actual behavior

Inferred type of accumulator and return value of Array#reduce is Record<string, unknown> in the provided examples.

🙂 Expected behavior

Inferred type of accumulator and return value of Array#reduce should be based on the type of the initial value.

Additional information about the issue

No response

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 el TypeScript Playground enlazado y compara la inferencia de Array#reduce en los ejemplos A–D, centrándote en los tipos del acumulador y del valor inicial. Confirma el comportamiento para Record<string, unknown> y los arrays con firma de índice; después, verifica que el acumulador y el tipo de retorno se basan en el valor inicial, tal como se muestra en el comportamiento esperado.

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
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.