microsoft / microsoft/TypeScript

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

Đang mở
#43,948 2 bình luận 0 reaction 1 người được giao Xem trên GitHub

@weswigham đang làm issue này rồi.

Từ ngày 13/5/2021.

Needs Investigation Rescheduled
Ngôn ngữ chính
Go
Star
111k
Fork
14.3k
Merge trung bình
2 ngày 4 giờ
Pull request đã merge (30 ngày)
132

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.