Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable type annotation for function declaration in Typescript? [duplicate]

Tags:

typescript

type Func = (foo:string) => void

// function expression
const myFunctionExpression:Func = function(foo) {
  console.log(foo)
}

In the Typescript snippet above, I am using type alias to annotate the variable in a function expression.

The type alias:

type Func = (foo:string) => void

is reusable in another function expression to reduce repetition.

My question is: Is there a way to reuse this type alias to annotate a function declaration ?

// function declaration
function myFunctionDeclaration(foo:string):void {
  console.log(foo)
}

After some search online, I cannot seem to find such syntax, what am I missing?

Thanks

update:

At the time of this writing there is a ticket on github requesting for this feature: Suggestion: Type annotations and interfaces for function declarations #22063 (thanks to comment from @jcalz)

like image 457
apollo Avatar asked Mar 18 '19 01:03

apollo


People also ask

What is type annotation in TypeScript?

Type Annotations are annotations which can be placed anywhere when we use a type. The use of Type annotation is not mandatory in TypeScript. It helps the compiler in checking the types of variable and avoid errors when dealing with the data types.

How do I create a return type function in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

How do you pass a function as a parameter in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.


2 Answers

At time of writing (TypeScript 3.4), there is not a way to apply a type to a function declaration.

like image 96
Ryan Cavanaugh Avatar answered Nov 02 '22 03:11

Ryan Cavanaugh


You can use the typescript utility types available from version 3.1 to achieve this.

  1. Parameters<Type> : https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype
  2. ReturnType<Type> : https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype

Example fitting the question:

Typescript Sandbox

type Func = (foo:string) => void

// function expression
const myFunctionExpression:Func = function(foo) {
  console.log(foo)
}
// function declaration
function myFunctionDeclaration(...[foo]: Parameters<Func>): ReturnType<Func> {
  console.log(foo)
}
like image 3
Blowsie Avatar answered Nov 02 '22 04:11

Blowsie