Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a Typescript function that complies to a type

Let's suppose I have declared a type containing defining a specific type of function

type Callback = (err: Error | null, result: any)
type UselessFunction = (event: string, context: any, callback: Callback) => void

I would like to declare functions that must comply to the type UselessFunction

I only found in the documentation how to assign a type to a function using arrow syntax

const someFunction: UselessFunction = (evt, ctx, cb) => {}

How can a type be assigned be function declaration? I cannot find the syntax in the docs

function someFunction (event, context, cb) {
}
like image 932
Valerio Avatar asked Sep 06 '25 21:09

Valerio


1 Answers

TypeScript lacks this functionality. You need to add the type annotation to the declaration's parameters and return value separately to make this function be of a specific type. You can, however, make it a bit more convenient by using Parameters and ReturnType types.

type UselessFunction = (event: string, context: any, callback: Callback) => void

function someFunction (...params: Parameters<UselessFunction>): ReturnType<UselessFunction> {
  // ...
}
like image 51
Mateusz Kocz Avatar answered Sep 08 '25 10:09

Mateusz Kocz