LearningMath
LearningMath

Reputation: 861

Typescript allowing property addition on a variable with an inferred type and complaining when type is explicit

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

Answers (1)

Alejandro Camba
Alejandro Camba

Reputation: 988

I think this answers will help you clarify your doubts:

SO question

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

Related Questions