Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
navneetkarnani opened this issue Aug 6, 2021 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@navneetkarnani
Copy link

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"

@jcalz
Copy link
Contributor

jcalz commented Aug 6, 2021

This doesn't really have much to do with Array.map(). You can reproduce the behavior like this:

function foo<K extends string>(k: K) {
    const o = { [k]: 123 }
    // const o: { [x: string]: number; }
    // not { [P in K]: number }
    // or more accurately { [P in K]: { [Q in P]: number } }[K]
};

Playground

which makes this a duplicate of #13948 and/or #21030.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 6, 2021
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants