4

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) {
}
1
  • If you type the individual parameters of someFunction, it should gain the type UselessFunction where necessary by duck typing Commented Feb 14, 2019 at 16:19

1 Answer 1

3

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> {
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.