When you have something like this (also see a playground):
functionmakeFoo<T>(fn: () => T): ()=>T{// do some work here ...returnfunction(){// ... or herereturnfn()}}constobj={name: 'test',foo: makeFoo(()=>obj.name.length)}type of obj will be infered as any, because in order to determine type of obj typescript first looks at return type of makeFoo(...) which uses obj.
The actual error is this: 'obj' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)
What if we could give some hint to a compiler to handle this case? Maybe like this:
constobj={name: 'test',foo: makeFoo(()=>obj.name.length)asprop// or a better name}Right now I have a workaround for this:
functiongetter<T,R>(t: T,k: keyofT,value: R){Object.defineProperty(t,k,{value,enumerable: true})returnvalue}constobj={name: 'test',getfoo(){returngetter(obj,'foo',makeFoo(()=>obj.name.length))}}but it would be cool if it could be done more easily.
When you have something like this (also see a playground):
type of
objwill be infered asany, because in order to determine type ofobjtypescript first looks at return type ofmakeFoo(...)which usesobj.The actual error is this:
'obj' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)What if we could give some hint to a compiler to handle this case? Maybe like this:
Right now I have a workaround for this:
but it would be cool if it could be done more easily.