GeezerVison is showing github.com — Contextual typing does not flow backward through function return types to the function arguments · Issue #5256 · microsoft/TypeScript
Contextual typing does not flow backward through function return types to the function arguments #5256DescriptionConsider the following case:
class Entry<T> {
constructor(callback: (v: T) => number) { }
}
interface Widget {
list: Entry<{ foo: number }>[];
}
var widget: Widget = {
list: [
new Entry((v) => v.foo), // Error accessing v.foo
]
};
We get a compiler error in the callback accessing v.foo that foo does not exist on type {} since {} is the default type when it is unable to infer the type. However, in this case we know from the Widget definition that T must be typed to {foo:number}. But, it appears TypeScript is not using this as an inference-site to properly determine T. ActivityRyanCavanaugh commented on Oct 14, 2015 More simply:
class Entry<T> {
constructor(callback: (v: T) => number) { }
}
var x: Entry<{foo: number}> = new Entry(v => v.foo);changed the title [-]Type inference is not using a type declaration annotation as an inference-site.[/-] [+]Contextual typing does not flow backward through function return types to the function arguments[/+] on Oct 14, 2015RyanCavanaugh commented on Oct 14, 2015 Let's go even simpler:
function foo<T>(x: (n: T) => T): T { return x(undefined); }
var x: string = foo(p => p.substr(2));
(placeholder since I need to write a longer explanation) drarmstr commented on Oct 21, 2015 RyanCavanaugh commented on Oct 21, 2015 Sorry, I forgot to write the follow-up I alluded to.
After walking through this with the spec, I think the rule we would need to support this is that a function call (or constructor call) contextually typed by T creates an inference site corresponding to the return type of that function or constructor.
That said, it's not clear what runtime semantics this rule corresponds to, or that it wouldn't be an undesirable breaking change. johnnyreilly commented on Oct 27, 2015 It would be fantastic if this could be looked into. RyanCavanaugh commented on Oct 31, 2016 Moving discussion to #11152 which has clearer explanation RyanCavanaugh commented on Sep 11, 2017 I believe this is fixed by #16072
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|