Skip to content

Why are generics not deducing nested objects correctly? #57658

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
masterYi2333 opened this issue Mar 6, 2024 · 2 comments
Closed

Why are generics not deducing nested objects correctly? #57658

masterYi2333 opened this issue Mar 6, 2024 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@masterYi2333
Copy link

🔎 Search Terms

Generic derivation

🕗 Version & Regression Information

  • This is a crash
  • This changed between versions ______ and _______
  • This changed in commit or PR _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
  • I was unable to test this on prior versions because _______

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.3#code/C4TwDgpgBAggdiAShAxgewE4BMoF4rLrYA8AzsBgJZwDmANFAIYIB8A3AFCiRQBmceKMQAqUCAA9gEOFlJQA3kwBcsBIUw4AviwAUYRhkYBbUisWMVwgNoAiRjYC6UTQEo8LKNbuPOHdHHIoACMVfkE9A2NSN1wPeQ4oRKgMCGAAVwwBfUMTADpGDk1ff0CUQSCdeMSLBQSkxgBGFQaAJgBmOjrNTtdOIA

💻 Code

// Your code here
type AnyRecord = Record<string, any>;
type fn = <T extends { a: AnyRecord }>(params: { a: T["a"] }) => T["a"];

const b: fn = (params) => {
    return params.a
};

const c = b({
  a: {
    a1: 123,
  },
});

🙁 Actual behavior

Why isn't c deduced to the type I actually passed in?

🙂 Expected behavior

c is deduced to the type I actually passed in

Additional information about the issue

No response

@Andarist
Copy link
Contributor

Andarist commented Mar 6, 2024

Indexed accesses like this are never used as inference sources - the information at this location is at best partial information for what T can be. That said, there is an open PR that would make this inference work: #53017

You can just infer into the whole T like this: TS playground

Or you can rewrite this signature using reverse-mapped types: TS playground

Using the technique above you can even benefit from excess property check in the upcoming TS 5.4: TS playground

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 6, 2024
@masterYi2333
Copy link
Author

thanks

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

3 participants