microsoft / microsoft/TypeScript

Unable to infer method property but able to infer arrow function property

Abierto
#43,948 2 comentarios 0 reacciones 1 asignado Ver en GitHub

@weswigham ya está trabajando en esto.

Desde el 13/5/2021.

Needs Investigation Rescheduled
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Bug Report

🔎 Search Terms

This issue came from StackOverflow question

🕗 Version & Regression Information

Since Object.fromEntries

⏯ Playground Link

Playground link with relevant code

💻 Code
const id = <T,>(x: T): T => x

const keys: string[] = []

/**
 * TS is unable to infer T generic argument of  fromEntries
 */
const fails = Object.fromEntries(keys.map(k => [
    k,
    id({ test() { } }) // <------ ERROR
]))

🙁 Actual behavior
const result: {
    [k: string]: T;
}
🙂 Expected behavior
const result: {
    [k: string]: {
        test(): void;
    };
}

I thought that it has smth to do with excess property checking, but it works if you replace id({ test() { } }) with id({ test:()=> { } })
Full list of workarounds:


/**
 * WORK
 */
const iter = keys.map(k => [
    k,
    id({ test() { } }) // ok
])
const obj1 = Object.fromEntries(iter)


const idResult = id({ test() { } })
const obj2 = Object.fromEntries(keys.map(k => [
    k,
    idResult
]))


const obj3 = Object.fromEntries(keys.map(k => [
    k,
    id({ test: () => { } }) // ok
]))


const obj4 = Object.fromEntries(
    keys.map<[string, { test(): void }]>((k) => [k, id({ test() { } })])
);


{
    interface Method {
        (): void;
    }
    const id = <T extends { [prop: string]: Method }>(x: T) => x;

    const keys: string[] = [];

    const obj = Object.fromEntries(keys.map((k) => [k, id({ test() { } })])); // ok

}

{
    type ArrowProp = () => any;
    const id = <T extends { [prop: string]: ArrowProp }>(x: T) => x;


    const obj = Object.fromEntries(keys.map((k) => [k, id({ test() { } })]));
}

{
    const id_ = <Prop, T extends Record<string, Prop>>(x: T) => x;
    // OR
    const id = <T extends object>(x: T) => x;
    const obj2 = Object.fromEntries(keys.map((k) => [k, id({ test() { } })]));
}

Playground

If I'm wrong and it is not a bug, could you please explain why TS is unable to infer method property?

I know that methods are bivariant, but I'm not sure if it has smth to do with current case

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.

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.