DEV Community

Cover image for A 'simple' TypeScript example
skube
skube

Posted on • Edited on

3 3

A 'simple' TypeScript example

When learning TypeScript it can seem verbose and confusing—if applied to the extreme. Take for instance a simple add function...

In JavaScript:

function add(x, y) { 
  return x + y;
};

// or as function expression
let add = function (x, y) {
  return x + y;
};

// or with ES6 fat-arrow
let add = (x, y) => x + y;
Enter fullscreen mode Exit fullscreen mode

In TypeScript, one could define types in several ways:

function add(x: number, y: number): number { 
  return x + y;
};


// or as function expression (type inferred on the _left_ operand)
let add = function (x: number, y: number): number {
  return x + y;
};

// or as function expression (type inferred on the _right_ operand)
let add: (x: number, y: number) => number = function (x, y) {
  return x + y;
};

// or as function expression (explicitly and somewhat redundantly)
let add: (x: number, y: number) => number = function (x: number, y: number): number {
  return x + y;
};


// or with ES6 fat-arrow (inference on left)
let add = (x: number, y: number): number => x + y;

// or with ES6 fat-arrow (inference on right)
let add: (x: number, y: number) => number = (x, y) => x + y;

// or with ES6 fat-arrow (😳)
let add: (x: number, y: number) => number = (x: number, y: number): number => x + y;
Enter fullscreen mode Exit fullscreen mode

Yikes! And that's with a really simple, pure function!

But really, we could narrow the types (by using const) and also let TS infer as much as possible:

function add(x: number, y: number) { 
  return x + y;
};
// Inferred type is function add(x: number, y: number): number


const add = (x: number, y: number) => x + y;
// Inferred type is let add: (x: number, y: number) => number
Enter fullscreen mode Exit fullscreen mode

All the same type safety, but with minimal verbosity! FTW.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay