Reputation: 861
If I have this piece of code:
const f = () => {}
f.newProperty ='new property'
TS allows it and further infers the type to be {(): void; newProperty: string}
But then if I have this code:
const f: () => void = () => {}
f.newProperty ='new property'
TS says that property newProperty
doesn't exist on the type () => void
.
Why is this so? My guess it that TS scanning the code at first collects every usage of the variable and then makes the final type inference, and in the second case I say the type and it doesn't try to infer it. But I'm not sure about this, because the following case breaks my reasoning. Suppose I have this code:
const obj = {}
obj.newProperty = ''
Here TS complains that newProperty
doesn't exist on the type {}
. I didn't specify the type of obj
explicitly like in the above second case, but it still complains. My expectation was that it would behave like in the above case with the function f
but it doesn't. Why is it so?
Upvotes: 0
Views: 38
Reputation: 988
I think this answers will help you clarify your doubts:
specifically, according to jcalz in the link:
Excess property checking, which is what you want, only happens in the specific situation where you use a fresh object literal.
Which is what is happening with the function declaration.
Here const f: () => void
type inference is disabled because you are specifying the type, like you said.
Upvotes: 1