function declaration issue with interface that has static properties

Viewed 131
interface IFn {
  (): number
  count: number
}
let fn: IFn = () => {
  return 1
}
fn.count = 0

Above code will occur an error:

Property 'count' is missing in type '() => number' but required in type 'IFn'.

But if I change let to const, the error disappears:

interface IFn {
  (): number
  count: number
}
const fn: IFn = () => {
  return 1
}
fn.count = 0

This is very confusing to me. I search a lot but get nothing, can someone help me? Thanks.


SOME UPDATE

If I define fn with const without assigning fn.count, I will get the same error.

interface IFn {
  (): number
  count: number
}
const fn: IFn = () => {
  return 1
}

if I assign fn with type assertion or Object.assign(), the "let" way is ok.

interface IFn {
  (): number
  count: number
}
let fn: IFn = (() => 1) as IFn
fn.count = 1

console.log(fn()) // 1
console.log(fn.count) // 1
interface IFn {
  (): number
  count: number
}
let fn: IFn = Object.assign(() => 1, { count: 1 })

console.log(fn()) // 1
console.log(fn.count) // 1

This problem seems to occur only when the interface has a function type definition(not very sure), here's a similar example and it will get an error:

interface IOjb {
  a: number
  b: number
}
const obj: IOjb = { a: 1 }
obj.b = 2
0 Answers
Related