简体   繁体   English

Typescript 中的 function 声明的可重用类型注释?

[英]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.在上面的 Typescript 片段中,我使用类型别名来注释 function 表达式中的变量。

The type alias:类型别名:

type Func = (foo:string) => void

is reusable in another function expression to reduce repetition.可在另一个 function 表达式中重复使用以减少重复。

My question is: Is there a way to reuse this type alias to annotate a function declaration?我的问题是:有没有办法重用这种类型的别名来注释 function 声明?

// 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)在撰写本文时,有一张关于 github 请求此功能的票:建议:function 声明的类型注释和接口#22063 (感谢@jcalz 的评论)

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

You can use the typescript utility types available from version 3.1 to achieve this.您可以使用 3.1 版提供的 typescript 实用程序类型来实现此目的。

  1. Parameters<Type> : https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype 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 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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