DEV Community

Cover image for A 'simple' TypeScript example
skube
skube

Posted on • Edited on

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.

Top comments (0)