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?