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
fn
should be of type() => void
based on your definition:playground
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
ofb
should have that type:{}
in TypeScript is used to represent something that can be any non-nullish value (anything that isn’tnull
orundefined
), meaning it’s not guaranteed to be a callable function.It looks like you are trying to call the
fn
function on theb
object, but you have not defined the type of thefn
function.To fix this error, you can define the type of the
fn
function by specifying the parameters and return type.For example: