简体   繁体   中英

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

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

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.

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

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

playground

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM