skip to Main Content

Well, I am learning TypeScript right now and am getting a problem. I do not know the reason.

When I call the function of an object, Visual Studio Code throws an error that type of {} has no call signatures.

I’ve tried to describe the type of function, but I failed.

console.log(b.<object>fn())
let b: { name: string; fn: {} }

b = {
  name: 'derek',
  fn: (): void => {
    console.log('i am a function')
  }
}

console.log(b.fn())

3

Answers


  1. fn should be of type () => void based on your definition:

    let b: { name: string; fn: () => void }
    

    playground

    Login or Signup to reply.
  2. In TypeScript, functions are usually typed using arrow notation to describe the function signature. So the type of a parameterless function that has no return value would be () => void.

    In your example, the property fn of b should have that type:

    let b: { name: string; fn: () => void }
    

    {} in TypeScript is used to represent something that can be any non-nullish value (anything that isn’t null or undefined), meaning it’s not guaranteed to be a callable function.

    Login or Signup to reply.
  3. It looks like you are trying to call the fn function on the b object, but you have not defined the type of the fn function.

    To fix this error, you can define the type of the fn function by specifying the parameters and return type.

    For example:

    let b: { name: string; fn: (x: number, y: number) => string }
    
    b = {
      name: 'derek',
      fn: (x: number, y: number): string => {
        return `The result is ${x + y}`
      }
    }
    
    console.log(b.fn(1, 2))  //"The result is 3"
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search