简体   繁体   中英

Reusable type annotation for function declaration in 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)

在撰写本文时(TypeScript 3.4),没有办法将类型应用于函数声明。

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM