LYJC
LYJC

Reputation: 13

How can I describe and call a function of a type of object in TypeScript?

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())

Upvotes: 0

Views: 261

Answers (2)

Dennis Kats
Dennis Kats

Reputation: 2299

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.

Upvotes: 1

akuiper
akuiper

Reputation: 215137

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

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

playground

Upvotes: 0

Related Questions