未加星标

Functional Patterns with TypeScript

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

Exploring if you can have your cake and eat it to.


Functional Patterns with TypeScript

Earlier this week, I found myself in conflict between my personal satisfaction in using TypeScript and the dissatisfaction recently expressed by a respected leader in the javascript community.

TypeScript continues to fall flat on its face for most higher order functions. Maybe I just don’t know how to use it correctly (after years living with it on a regular basis ― in which case, they really need to improve usability, documentation, or both), but I still don’t know how to properly type the map operation in TypeScript, and it seems to be oblivious to anything going on in a transducer. It fails to catch errors, and frequently complains about errors that aren’t really errors at all.

― Eric Elliot ― Top JavaScript Frameworks and Topics to Learn in 2019

Having read and written on Eric Elliot’s excellent series on functional programming with JavaScript, starting with Composing Software: An Introduction , I thought to revisit some functional patterns with TypeScript .

Functors

One interesting, and more complicated, pattern is a functor.

A functor data type is something you can map over. It’s a container which has an interface which can be used to apply a function to the values inside it. When you see a functor, you should think “mappable”. Functor types are typically represented as an object with a.map() method that maps from inputs to outputs while preserving structure. In practice, “preserving structure” means that the return value is the same type of functor (though values inside the container may be a different type).

― Eric Elliot ― Functors & Categories

While JavaScript arrays with their map method, are functors, we can create our own in JavaScript (example courtesy of Eric Elliot ), e.g., the objects ( a and c ) returned by identity function:

Edit 1/4/19: Turn out that in my first pass at this, I neglected to return a functor from the map function; big mistake . Also, added some more complex mapping functions, especially conversion that switches types (from number to string) to make the problem more challenging.

In the above JavaScript example, we deliberately misuse the c functor, trying to multiply a string by 2, and thus getting an unexpected run-time result; it actually returns the same string; cat .

Let us rewrite this code in TypeScript :

note: One of the complicated parts of TypeScript is Generics ; assuming the reader is familiar with this concept.

Edit 1/4/19: Obviously, since I changed the JavaScript example, I was forced into changing the TypeScript example.

Converting this from JavaScript to Typescript amounted to creating a Mappable interface and very carefully supplying the types for various parameters and return types.

In the above TypeScript example, we again deliberately misuse the c functor, trying to multiply a string by 2. This time, however, we get a compile time error (as shown in my editor, Visual Studio Code , with a completely understandable error message.


Functional Patterns with TypeScript
Object Progression

Eric Elliot also describes an interesting approach to implementing increasing complexity:

Start with the simplest implementation, and move to more complex implementations only as required. When it comes to objects, that progression looks a bit like this:

― Eric Elliot ― Functional Mixins

Earlier I wrote an article, Examples in JavaScript Functional Programming: Part 3 , where I created examples of each of the patterns, in particular:

Thought to use a series of simple and consistent examples to demonstrate this guidance. For familiarity sake, all the examples involve a calculation of a line:

― John Tucker ― Examples in JavaScript Functional Programming: Part 3

Let use recreate those examples in TypeScript ; exploring any challenges we encounter:

Pure Function

The simplest way to deliver reusable code is through a pure function.

A pure function is a function where the return value is only determined by its input values, without observable side effects. Some common things to avoid:

Do not mutate the input, e.g., Array.prototype.push() . Do not use (changeable) variables outside of the function’s scope.

Converting this from JavaScript to Typescript simply amounted to supplying the number type on function’s parameter ( x ); the return value is inferred.

In this and the following examples, we gain valuable type safety (with compile-time checks). For example, in JavaScript we could have misused myPureFunction by supplying it a string with an unexpected runtime result. In TypeScript this would have resulted in a compile-time error (visible in one’s editor).

Object

We can use an object literal to deliver the same reusable code, but adding the capability of changing the slope and intercept. It is important to note that there is only one object (a singleton).

Converting this from JavaScript to Typescript simply amounts to supplying the parameter and return types, both number , on the y method.

One interesting thing that I learned while writing this article is that with TypeScript , this is typed as any ; explaining why we need to explicitly provide the return type.

Factory

We might want to have more than one such object; each with its own slope and intercept.

Converting this from JavaScript to Typescript is a little more complicated as we need to define the object’s structure using a MyObject interface; outside of this we only needed to supply the parameter and return types for the three methods setIntercept , setSlope , and y .

Functional Mixin

The additional complexity of function mixins allow you to create objects that derive functionality from multiple sources. In this example, we have two objects ( objectA and objectB ) that are enhanced with the functionality from myFunctionalMixin .

This is the most complicated example to convert to TypeScript as we need to use Generics . At the same time, the changes only amount to creating the MyMixedObject interface and supplying parameter and return types on several functions.

Class Much lik

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Functional Patterns with TypeScript
本站链接:https://www.codesec.net/view/628597.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(162)