简体   繁体   中英

TypeScript - the best approach for typing functions?

I'm learning TypeScript, and I have a question around annotating types of functions.

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.

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. Sure. My linter shuts up about missing return types in either.

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? 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);

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