microsoft / microsoft/TypeScript

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

Offen
#43,948 2 Kommentare 0 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@weswigham arbeitet bereits daran.

Seit 13.5.2021.

Needs Investigation Rescheduled
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.