zzzgoo
zzzgoo

Reputation: 2235

Can I define a type of non-arrow function in ts?

In TypeScript, I can define a function type like this:

type MyCallback = (para: number|string)=> string

These functions will be used as event callbacks, so I want a normal function rather than arrow functions to avoid this issues occurring in arrow functions.

Is there a way to define a type that only allows normal functions?

Upvotes: 4

Views: 1883

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

Typescript actually doesn't distinguish between arrow functions and regular functions when it comes to the type of a function. So the you are fine using the arrow function type to represent any callback:

type MyCallback = (param: number|string)=> string

function onValue(fn: MyCallback) {
  return fn(0)
}

onValue(o => o.toString())
onValue(function (o) { return o.toString() })

Playground Link

There is a non arrow syntax for function signatures, but it's usually used when you have to define overloads:

type MyCallback = {
  (param: string): string
  (param: number): string
}

Playground Link

Upvotes: 2

Related Questions