microsoft / microsoft/TypeScript
Unable to infer method property but able to infer arrow function property
Open
@weswigham is already working on this.
Since May 13, 2021.
Needs Investigation
Rescheduled
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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() { } })]));
}
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.