Skip to content

Array.map() returns {[key:string]: string} when it should return {[key:T]: string} #45344

@navneetkarnani

Description

@navneetkarnani

Bug Report

🔎 Search Terms

array map reduce type inference

🕗 Version & Regression Information

Seen on all versions. I have tested on: 4.4.0-dev.20210806 in playground

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "This mapped type returns a primitive type, not an object type."

⏯ Playground Link

Playground link with relevant code
)

💻 Code

// create a getEnv function that will
// return an object with key is supplied name
// and value is a "computed/derived/other value", 
// typically process.env[name]
const getEnv = <T extends string>(...envNames: ReadonlyArray<T>): Record<T, string> => {
    
    const newObj = envNames.map( name => { 
        return {[name]: name as string};
    }).reduce((prev, curr) => {
        return { ...prev, ...curr };
    });

    // Bug: notice that "newObj" is not type Record<T, string> but Record<string, string>
    return newObj;
};

// @errors: expect that the "hello" variable here should result in a compilation failure, or "hello" should be "never"
const { myName, hello } = getEnv('myName');

🙁 Actual behavior

array.map().reduce() returns object with type Record<string,string>

🙂 Expected behavior

array.map().reduce() should return object with type Record<T,string> because the "key" in the map function is limited by value scope to the values in "T"

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions