简体   繁体   English

TypeScript - 键入函数的最佳方法?

[英]TypeScript - the best approach for typing functions?

I'm learning TypeScript, and I have a question around annotating types of functions.我正在学习 TypeScript,我有一个关于注释函数类型的问题。

Looking at this simple example:看这个简单的例子:

export const add = (num1: number, num2: number):number => {
  return num1 + num2;
};

This feels well typed to me.这对我来说感觉很好。 The arguments have a type and the function's return type is also annotated. arguments 有一个类型,函数的返回类型也有注释。

Now consider this, also valid syntax:现在考虑一下,这也是有效的语法:

export const add2:(num1: number, num2: number) => number = (num1, num2) => {
  return num1 + num2;
};

We're typing the variable add2 itself.我们正在输入变量add2本身。 Sure.当然。 My linter shuts up about missing return types in either.我的 linter 对其中任何一个都缺少返回类型而闭口不谈。

I could even do both:我什至可以两者都做:

export const add3:(num1: number, num2: number) => number = (num1: number, num2: number):number => {
  return num1 + num2;
};

My question is - are there any advantages or disadvantages to doing approaches 1, 2 or 3 here?我的问题是 - 在这里做方法 1、2 或 3 有什么优点或缺点吗? Is there a more idiomatic style amoung them?他们之间有更惯用的风格吗?

When you declare new variable and assign it in the same statement there is no need to explicitly specify the type - it will be assumed automatically.当您声明新变量并在同一语句中分配它时,无需显式指定类型 - 它将自动假定。 So for the use cases in your question first option will be the most optimal.因此,对于您问题中的用例,第一个选项将是最佳选择。

If you need to declare a variable and assign a value(function) to it later - the cleaner way to do this is to use Interfaces.如果您需要声明一个变量并稍后为其分配一个值(函数) - 更简洁的方法是使用接口。 Something along these lines:这些方面的东西:

interface AddFunc {
  (num1: number, num2:number): number;
}

let add: AddFunc;
add = (a: number, b: number): number => a + b;
add(1, 2);

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

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