microsoft / microsoft/TypeScript
Unable to infer method property but able to infer arrow function property
Aperta
@weswigham ci sta già lavorando.
Dal 13/5/2021.
Needs Investigation
Rescheduled
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Valutazione
Questa issue non è ancora stata valutata.