Skip to main content

Is Typescript a functional language

The answer to this question is both Yes and No. Similar to many other popular programming languages like Java, Typescript is also trying to combine best of both worlds for its users. Typescript is a multi-paradigm programming language and it is has influences from Object Oriented Programming as well as fucntional programming paradigm.

One of the most important concept of functional paradigm is that the languages following this paradigm ensure that the applications builts using their type system are free of side-effects. Since Typescript interoperate with Javascript, it has lost some of its freedom and unlike pure functional languages like Haskell it cannot guarantee that our applications will be free from side-effects. Languages like Haskell ensure this through their type system. We can however use FP techniques to improve our type safety. For example look at the following code snippet

findNumber (numbers: Number[], input: number): number {
   if(numbers.length == 0) {
      throw new Error ("There are no number");
   }

   const number = numbers.find ( (num, index ) => {
       if(input === num ) return index
    });

   if( number) return number;
   throw new Error("Number not found!");
}
 
const numbers = [2, 3, 5, 21, 45, 56, 23, 2, 456];
const numberIndex = findNumber(numbers, "3"); 
console.log(`Number found at index ${numberIndex}` );

const numberIndex2 = findNumber([], "3")
console.log(`Number found at index ${numberIndex2}` );

You can see that the second call to findNumber will not return a number instead it will throw an error. That means the function canot guarantee a specific type of output in all situations. This is againt the functional programming paradigm.

In Functional programming languages like Haskel the default behavior of type system ensures that this will not happen. In Typescript it is up to the programmer to use an approach like the above or choose a more functional way through promises. A promise based approach will look like the following

findNumber (numbers: Number[], input: number) : Promise<number> {
   if(numbers.length == 0) {
      return Promise.reject(new Error("There are no numbers") );
   }

   const number = numbers.find ( (num, index ) => {
       if(input === num ) return Promise.resolve(index)
    });

   if( number) return number;
   return Promise.reject(new Error("Number not found") );

}
findNumber(numbers, "3").then ( idx => console.log(`Number found at index ${idex}` ) 
The above example shows how we can transform our unsage and impure function into a safe and pure function.

The answer of our original question is Typescript is both functional and object oriented and it allows programmers to choose the implementation based on what they find easy for their problems.

Comments

Popular posts from this blog

Html5 Canvas Drawing -- Draw dotted or dashed line

This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line. var canvas = document . getElementById ( "canvas" ); var ctx = canvas . getContext ( "2d" ); ctx . setLineDash ([ 5 , 3 ]); /*Dash width and spaces between dashes.*/ ctx . beginPath (); ctx . moveTo ( 0 , 100 ); ctx . lineTo ( 400 , 100 ); ctx . stroke (); If you want to draw lines having a custom style there is no methos in the API. But fortunately there is a way to achieve this. Following is a description about how I achieved this. You can set the stroke pattern on canvas context. Stroke pattern can be created using any image. You create image for your custom pattern and set strokeStyle of the context like the following: var linePattern; imageToUsedAsPattern.onload = function() { linePattern = context.createPattern(imageToU...

Angular Directives

Word Direcitve means something that serves to direct or guide towards an action or goal. The purpose of Directives is similar in Angular too. Directives are basically markers for DOM elements and are used to either create new HTML elements or extend behavior of already present elements. There are three types of Directives Component Directive Strucutral Directive Attribute Directive To create a directive in Angular2, you have to follow these steps Create a regular javascript class and decorate it with @Directive decorator import { Directive } from '@angular/core' ; @Directive ({ selector : "[disableOnClick]" , }) class DisableOnClick { @ HostListener ( 'click' , [ '$event.target' ]) onClick ( element ) { element.disabled= "disabled" } } Declare it in your module declaraion file e.g app.module.ts import { NgModule } from '@angular/core' ; import { DisbaleOnClick } from './...

Angular2+: ng-template

This is an angular element which is used to render HTML, it never gets displayed directly. It is used by structural directives like ngIf and ngFor. We can use them directly in some cases e.g when we want to reuse a template multiple times in our code. Suppose we have following code <ng-template> <p> Hello World! </p> </ng-template>  When it will run the code inside it will not get displayed. If you will inpect the HTML in your developer console you will see that the above will get replaced by a comment and you will find only following in its place. <!----> Now this doesn't make sense that angular is giving a component which just eats up your code and does nothing. This component is actually used to create a reusable template which can be accessd via a tempalte reference. It is used internally by angular to replace the structure directives with it and later at run time is converted into a comment. So for example if you have an ngFor in ...