Home > Blockchain >  how can i describe and call a function of a type of object in typescript?
how can i describe and call a function of a type of object in typescript?

Time:01-08

well,I am learning typescript right now and getting a problem.i do not know the reason.hopeing someone can solve this when I call the function of a object.vscode throw a error that type of {} has no call signatures. I've tried 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())

CodePudding user response:

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.

CodePudding user response:

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

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

playground

CodePudding user response:

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"

  • Related