<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hernan Rajchert on Medium]]></title>
        <description><![CDATA[Stories by Hernan Rajchert on Medium]]></description>
        <link>https://medium.com/@hernanrajchert?source=rss-9e165ef458c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zvt_ytUOpdXLqaHd44XPYw.jpeg</url>
            <title>Stories by Hernan Rajchert on Medium</title>
            <link>https://medium.com/@hernanrajchert?source=rss-9e165ef458c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:09:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hernanrajchert/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Guardianes del código]]></title>
            <link>https://medium.com/@hernanrajchert/guardianes-del-c%C3%B3digo-6cb69e1f93f1?source=rss-9e165ef458c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cb69e1f93f1</guid>
            <category><![CDATA[programacion-funcional]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hernan Rajchert]]></dc:creator>
            <pubDate>Thu, 08 Nov 2018 23:40:33 GMT</pubDate>
            <atom:updated>2018-11-08T23:40:33.778Z</atom:updated>
            <content:encoded><![CDATA[<p>Como desarrolladores, no queremos utilizar el tiempo de nuestros sprints debuggeando bugs, y no queremos ser llamados a las 8 de la noche de un Sábado porque nuestro software está roto. Queremos tener confianza en lo que hacemos, necesitamos un héroe que nos res<strong>guard</strong>e y proteja de los errores que podrian ser fácilmente evitados. Necesitamos programar más defenisvamente! Necesitamos… contratos???</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Ke0Nfo5y09Ch8Kq0RANzzQ.gif" /><figcaption>El comportamiento inesperado puede causar bugs</figcaption></figure><h4>Contratos al rescate!</h4><p>Cada vez que programamos definimos contratos, aún si no lo hacemos conscientemente, cuando definimos una función, definimos un contrato en el que declaramos los parámetros que recibe y la relación y restricciones que pueden tener. Cuando llamamos a una función, estamos aceptando sus “Términos y Condiciones”, y si es código de terceros el contrato seguramente esté definido en forma de documentación.</p><p>El método Array.indexOf es un excelente ejemplo. Como se describe en la <a href="https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/indexOf">documentación</a> podemos usarlo para buscar si un elemento existe en el Array. Tiene dos posibles argumentos, el primero es <strong>obligatorio</strong>, y el segundo es opcional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dm8siMeK8iIa8WymST8WHw.png" /><figcaption>Método indexOf de los arrays de JavaScript</figcaption></figure><p>Vale la pena notar todas las condiciones relacionadas al segundo argumento. Qué pasa si no lo pasamos? Qué pasa si es un valor negativo? Qué pasa si es un número mayor al tamaño del Array? Qué pasa si cometemos un error y pasamos un string?</p><p>Si fuésemos a programar esta función nosotros mismos, probablemente haríamos algo como esto:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82f6b77cfa47775902a6a96d13d51f7d/href">https://medium.com/media/82f6b77cfa47775902a6a96d13d51f7d/href</a></iframe><p>Donde definimos <strong>pre-condiciones</strong> que nuestros parámetros deben satisfacer antes de hacer el trabajo en sí. Estas <strong>pre-condiciones</strong> son también conocidas como <strong>Guards</strong>, como podemos ver en la <a href="https://en.wikipedia.org/wiki/Guard_(computer_science)">definición en Wikipedia</a>:</p><blockquote>En programación, un guard es una expresión booleana que debe ser evaluada como verdadera para que el programa continúe por la rama en cuestión. Independientemente del lenguaje de programación usado, una <strong>clausula de guard</strong> es un chequeo de integridad llamado precondición, y es usado para evitar errores durante la ejecución.</blockquote><p>Para hacer que nuestros contratos sean más seguros podríamos también definir <strong>post-condiciones</strong>, que como su nombre implican, son ejecutadas después del código de la función. En el caso de <em>indexOf </em>podríamos asegurarnos de que la respuesta es un número que represente la posición del array o el valor -1.</p><p>Tanto las <strong>pre</strong> y <strong>post</strong> condiciones nos dan garantías sobre cómo programamos. Las primeras protejen a nuestras funciones de quien las llame, y las segundas protejen al código de sí mismo.</p><h4>TypeScript A Todo Ritmo</h4><p>Una de las ventajas de usar <strong>guards</strong> es que siguen el principio de fallar lo más rápido posible. En vez de dejar que nuestros errores se propaguen o sean ignorados silenciosamente, nos van a tirar una advertencia apenas vean el error y nos ayudarán a encontrar el origen del problema.</p><p>Para fallar aún más rápido, podemos usar un <strong>chequeo de tipos estáticos</strong> como TypeScript. Funciona como la policía de nuestros programas, enforzando los contratos que definimos en tiempo de compilación. En el siguiente ejemplo refactorizamos una de las <strong>pre-condiciones</strong> usando anotación de tipos:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceafbdc7578c581e055f180848a52476/href">https://medium.com/media/ceafbdc7578c581e055f180848a52476/href</a></iframe><p>Si llamamos a la función y no respetamos su contrato vamos a tener un error en tiempo de compilación, lo que significa ciclos de desarrollo más rápidos, ya que no tenemos que probar el código si tenemos un error, el compilador nos dará una pista de qué tenemos que arreglar.</p><p>Nuestra complejidad mental claramente ha aumentado, ya que entender el concepto de generics es más complicado que una <em>sentencia if</em>, pero ganamos más garantías. Una pregunta que no nos hicimos antes es: qué pasa si tenemos una lista de números <strong>[1, 2, 3]</strong> y buscamos por un string, por ejemplo <strong>“3”</strong>? La respuesta probablemente sea lo esperado, recibimos un -1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b34883de062ba7206ca54219aea07929/href">https://medium.com/media/b34883de062ba7206ca54219aea07929/href</a></iframe><p>Si no usamos un type checker, no nos daremos cuenta que estamos violando el contrato de <em>indexOf</em> y tendremos un bug silencioso (que no tira un error). Si usamos TypeScript tendremos un error en tiempo de compilación que nos hará reflexionar sobre la verdadera pregunta: Por qué estamos buscando un string en un array de números en primer lugar?</p><p>También podemos agregar un tipo de retorno a nuestra función para que funcione como una <strong>post-condición</strong>, enforzandonos a devolver un número. Vale la pena notar que <em>no todos los type systems son creados iguales</em>, y te pueden dar distintas garantías. Por ejemplo, TypeScript <strong>no puede</strong> obligarte a devolver un número en el rango correcto, mientras que un lenguaje más restrictivo con el concepto de Dependent Types, como <a href="https://www.idris-lang.org/">IDRIS</a>, sí puede.</p><h4>Type guards</h4><p>TypeScript tiene un concepto llamado Type Guards que está relacionado con lo que venimos hablando, pero en vez de <em>continuar o no la ejecución del programa</em>, va a poder achicar el tipo inferido de una variable en un scope dependiendo de algunos chequeos dinámicos.</p><p>Consideremos el siguiente código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4d67a3127b62add4cbe1be725ce334/href">https://medium.com/media/ce4d67a3127b62add4cbe1be725ce334/href</a></iframe><p>Si lo corremos en la consola de JavaScript y el elemento existe, todo estará bien, pero si no existe tendremos el <strong>error en tiempo de ejecución</strong>: <em>Cannot set property ‘innerHTML’ of null.</em></p><p>Si usamos TypeScript con la opción <em>strictNullCheck </em>habilitada, la función <em>getElementById </em>va a devolver la <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types">unión de tipos</a> “<em>HTMLElement | null</em>”. Entonces no importa si el elemento existe o no, tendremos un <strong>error en tiempo de compilación</strong> diciendo que el objeto tal vez sea null.</p><p>Agregando un simple <em>if</em> podemos solucionar el error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e0a47587cedf639450b92058224254/href">https://medium.com/media/f2e0a47587cedf639450b92058224254/href</a></iframe><p>Esto es posible gracias a los <strong>Type Guards</strong>. TypeScript usa “análisis de flujo” para tratar de entender todos los posibles tipos que una variable puede tener en distintas partes del código. En la primera linea, <em>header</em> puede ser <em>“HTMLElement | null”</em>, la única forma de llegar a la línea 4 es si <em>header </em>es thrutly, así que TypeScript va a achicar su tipo a <em>HTMLElement</em>. De la misma manera, la única forma de llegar a la línea 6 es si el header es falsy, entonces el tipo será <em>null</em>.</p><p>Los Type Guards también pueden ser usados para definir “tipos de datos algebraicos” (ADT) para separar la lógica de los datos. Examinemos el siguiente código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47c9bcd0953244b086affc521208f7c/href">https://medium.com/media/a47c9bcd0953244b086affc521208f7c/href</a></iframe><p>Adentro de la función <em>doYourThing </em>no sabemos mucho sobre <em>animal</em>. Sabemos que tiene una propiedad llamada <em>species</em>, ya que tanto <em>Cat</em> y <em>Dog</em> tienen una propiedad con ese nombre. El tipo de la propiedad será la unión de los posibles tipos, en este caso <em>‘cat’ | ‘dog’.</em></p><p>La única forma de llegar a la línea 19 es si <em>species</em> es igual a<em> ‘dog’</em>, asi que el Type Guard va a achicar el tipo de <em>animal</em> a <em>Dog</em> en ese bloque, permitiendonos usar la propiedad <em>favoriteHuman</em>. De la misma manera, si llegamos a la línea 21 es porque <em>animal</em> es del tipo <em>Cat</em>, por lo que tendrá la propiedad <em>nemesis</em>.</p><p>No deberiamos poder llegar a la línea 23, porque <em>species</em> sólo puede ser <em>‘cat’</em> o<em> ‘dog’</em> y ambas condiciones fueron chequeadas dentro de la función, entonces el Type Guard concluye que en ese bloque el tipo de <em>animal</em> es <strong>never</strong>. Esto nos permite hacer algo llamado chequeo exhaustivo, un patrón que nos obliga a contemplar todos los valores posibles del ADT. Si agregamos un nuevo tipo de <em>Animal</em> en la línea 11 y no modificamos nuestra función, obtendremos un error porque no le podremos pasar ese animal a la función <em>assertNever</em>.</p><p>En <a href="https://youtu.be/d1f6VBmWg6o?t=42m1s">esta charla</a> podemos ver una demostración de este feature de la mano de <a href="https://twitter.com/ahejlsberg">Anders Hejlsberg</a>, uno de los desarrolladores principales del lenguaje.</p><h4>Custom Type Guards</h4><p>TypeScript viene con una variedad de Type Guards ya predefinidos. Tenemos <em>instanceOf</em>, <em>typeOf</em>, y los <em>literal values</em> directamente disponibles, pero hay algunos escenarios donde necesitamos definir nuestros propios Type Guards.</p><p>El concepto que usamos en la sección anterior para crear nuestros ADTs se llama <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions">unión discriminada</a>, en donde nos aprovechamos que todos los tipos de la unión comparten una misma propiedad con valores distintos que nos permite saber el tipo de nuestro objeto. Pero qué pasa si los tipos no son tan homogéneos?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551eec1c5c0119471ddb24e98b2ac624/href">https://medium.com/media/551eec1c5c0119471ddb24e98b2ac624/href</a></iframe><p>Este código nos tirará un error de compilación en la línea 15, ya que TypeScript no puede asumir que <em>feline</em> tiene una propiedad llamada <em>species</em>. Si tratamos de darle una pista al compilador, casteando el valor a <em>Cat</em>, romperemos el Type Guard, y eso nos tirará un error en la función <em>assertNever</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3caa8fc38c5c6f4fce1fa69a45c2d43/href">https://medium.com/media/f3caa8fc38c5c6f4fce1fa69a45c2d43/href</a></iframe><p>Para hacer que este ejemplo funcione tenemos que crear un Type Guard custom, que no es nada más que una función que devuelve un booleano. La sintaxis es bastante fácil, recibis un parámetro <strong>x</strong> con un tipo más general y devolves <strong>x is foo</strong> para indicar que si la condición es cierta, entonces <strong>x</strong> es del tipo <strong>foo</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/470cffb99921bccecb4df86d2b5a5f25/href">https://medium.com/media/470cffb99921bccecb4df86d2b5a5f25/href</a></iframe><p>Y ahora nuestro ejemplo funciona correctamente 👍. Si queres ver un ejemplo real de cómo se pueden usar los custom type guards, podes fijarte como usamos la función <a href="https://github.com/ts-task/utils#isinstanceof">variadica isInstanceOf</a> y <a href="https://github.com/ts-task/utils#caseerror">caseError</a> para manejar correctamente nuestros errores usando <a href="https://github.com/ts-task/task">Task</a>. Acá les dejo un <a href="https://www.youtube.com/watch?v=Bm0eIBZYRZw">vídeo</a> de una lightning talk que di en Meetup.js en el que se ve el que muestro todo eso 😉.</p><p>Eso es todo por ahora! Díganme que les pareció el artículo en twitter <a href="http://www.twitter.com/@sherman3ero">@sherman3ero</a>, todo el feedback es bienvenido❤️.</p><p>Generalmente escribo sobre TypeScript y programación funcional. Por favor díganme los temas que les gustaría leer.</p><p>Saludos 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cb69e1f93f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript conoce a Google Sheets]]></title>
            <link>https://medium.com/@hernanrajchert/typescript-conoce-a-google-sheets-b96a6d2937b3?source=rss-9e165ef458c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b96a6d2937b3</guid>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[programacion-funcional]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[app-script]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Hernan Rajchert]]></dc:creator>
            <pubDate>Fri, 26 Oct 2018 23:22:28 GMT</pubDate>
            <atom:updated>2018-10-26T23:22:28.782Z</atom:updated>
            <content:encoded><![CDATA[<p>Lo dije <a href="https://www.youtube.com/watch?v=DKliwV3QdnU&amp;feature=youtu.be&amp;t=466">antes</a> y lo diré de nuevo, Google Sheet es una herramienta espectacular para aprender algunos conceptos de programación funcional. Por ejemplo, el hecho de que no nos importe si una celda es un valor constante o el resultado de una función nos debería gritar <a href="https://es.wikipedia.org/wiki/Transparencia_referencial">transparencia referencial</a>. También, la forma en la que escribimos lógica condicional se parece más al operador ternario que a la <em>sentencia if</em> imperativa, lo que nos muestra cómo podemos construir un programa en donde todo es una expresión.</p><p>Pero no todo es color de rosas, las funciones de Google Sheet no pueden componerse para formar nuevas funciones, que es el abc de la programación funcional. Eso hace que tengamos expresiones muy grandes si nuestra lógica es complicada. Por suerte para nosotros, Google Sheets tiene una relación abierta con AppScript/JavaScript y por otro lado TypeScript es una forma de tipar JavaScript, así que pensé que los dos se deberían conocer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZa3sk2vrAZNS4JYBrcT-A.png" /></figure><h3>Pero por qué?</h3><blockquote>Tus cientificos estaban tan preocupados con saber si podían hacerlo, que no se detuvieron a pensar si deberían — Dr. Ian Malcolm, Jurassic Park</blockquote><p>Esta pregunta tiene dos partes, por un lado, por qué usar Google Sheets, por otro lado por qué extenderlo con JavaScript/TypeScript.</p><p>Google Sheets es un entorno de programación multi-propósito con una barrera de entrada muy baja. Lo he usado personalmente para crear <a href="https://www.analiticaweb.es/metricas-para-piratas-aarrr/">reportes AARRR</a> que ayudan a mi empresa a tomar decisiones de negocio, reportes de balance para ver donde estoy económicamente hablando y últimamente me armé una planilla para ayudarme a organizar un futuro viaje en bicicleta por Europa 🚲. El mayor beneficio es que podemos concentrarnos en nuestros datos y la lógica de negocios y más o menos olvidarnos de la UI.</p><p>Como mencioné previamente, si nuestra lógica se vuelve lo suficientemente compleja, tal vez queramos usar un lenguaje de programación más completo creando un App Script, que es una solución agregada al G-suite en el 2009 y es compatible con la mayoría de los features disponibles en <strong>E</strong>cma<strong>S</strong>cript<strong>5</strong>. Actualmente, en el 2018, <strong>ES5</strong> puede parecer anticuado, pero por suerte para nosotros, podemos usar un compilador/transpilador como TypeScript para obtener algunos de los últimos features del lenguaje, como <a href="https://desarrolloweb.com/articulos/arrow-functions-es6.html">arrow functions</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a> y <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring</a>.</p><p>También nos podemos beneficiar de tener un type checker que nos avise si estamos haciendo algo mal. Tuve que hacer mucha prueba y error para darme cuenta que cuando pasamos un rango de una columna de números como argumentos a AppScript, no recibimos un simple array, sino un array de arrays. La parte que más confundía tenía que ver en como JavaScript hace la coerción de tipos, mis ejemplos funcionaban para algunos casos pero no para otros. Si usamos un type checker y tipamos correctamente a los rangos, podemos tener una advertencia sin siquiera correr el código.</p><p>Esto me recuerta que el año pasado para esta época me fui de viaje a San Luis Argentina, donde el WIFI es gratis pero la conexión puede variar dependiendo de donde estas. Allí decidí hacer mi reporte de balance personal y usando un starter kit de TypeScript que ya tenía instalado en mi computadora y creando algunos test unitarios, supe que mi código funcionaba sin tener que probarlo en Google Sheet 🎉.</p><h3>Primera cita</h3><p>Ahora que las introduciones fueron hechas, bajemos las luces, pongamos a Marvin Gaye y <a href="https://www.lanacion.com.ar/2180510-la-palabra-del-momento-que-significa-skere">skere</a>!. Empezaremos haciendo un simple Hola Mundo.</p><p>Primero creamos una nueva planilla en Google Sheet y en el menú de <em>Herramientas</em>, seleccionamos <em>editor de secuencia de comandos</em>. Esto nos abrirá un editor web en una nueva terminal. Escribimos la función de hola mundo, salvamos con cualquier nombre y en alguna celda invocamos la nueva función como si fuera una nativa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rNH7w3r4ZTxmYopV" /><figcaption>Hello World con App Script</figcaption></figure><p>Ahora que el ambiente está listo, vamos a ver si podemos traer a TypeScript a la fiesta. En la <a href="https://developers.google.com/apps-script/guides/typescript">documentación oficial</a>, hay un ejemplo de como integrarlo usando la herramienta de consola clasp. Pero nosotros usaremos el <a href="https://github.com/alexjoverm/typescript-library-starter">Library starter</a> de <a href="https://medium.com/u/82ac64561d1">Alex Jover Morales</a> para armar el proyecto, porque esto es después de todo, una librería que usaremos desde nuestro programa, Google Sheet. En alguna entrada posterior podemos explorar cómo modificar el starter para subir el código usando clasp.</p><p>Abrimos una terminal y ponemos los siguientes comandos:</p><pre>$ git clone <a href="https://github.com/alexjoverm/typescript-library-starter.git">https://github.com/alexjoverm/typescript-library-starter.git</a> ts-integration-test<br>$ cd ts-integration-test<br>$ npm install</pre><p>Seguimos las instrucciones, y una vez instalado usamos nuestro editor favorito para modificar <strong>ts-integration-test.ts</strong> para que sea</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fac339b474ed4c99eef38d7b9906bc5/href">https://medium.com/media/4fac339b474ed4c99eef38d7b9906bc5/href</a></iframe><p>Ahora podemos compilar la librería en la terminal usando el comando <strong>npm run build</strong>, que generará un archivo llamado <em>dist/ts-integration-test.umd.ts </em>con el siguiente contenido:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3cc44e50f8337bfec2cd4adc24a7df0/href">https://medium.com/media/c3cc44e50f8337bfec2cd4adc24a7df0/href</a></iframe><p>Esto es una <a href="https://github.com/umdjs/umd">definición de módulo universal (UMD)</a>, y está pensada para ser corrida en el servidor usando node, en el browser, y por qué no, en Google Sheets. Si prestamos atención a la linea 4 tendremos una pista de cómo podemos usar esto en nuestro ejemplo.</p><p>Primero, en el Editor de código, creamos un nuevo archivo llamado <em>bundle.gs</em> y copiamos el contenido del archivo umd. Luego modificamos nuestra función <em>HELLO</em> para que devuelva el resultado de llamar a <em>tshello</em> dentro del namespace <em>tsIntegrationTest</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tNAOxtrO7rK5A6cM" /><figcaption>Hello World con TypeScript</figcaption></figure><p>Con estos simples pasos creamos una librería de TypeScript que puede ser llamada desde nuestra planilla y que tiene la habilidad de ser testeada unitariamente con <a href="https://jestjs.io/">Jest</a>, hacer commits semanticos con <a href="https://github.com/commitizen/cz-cli">commitizen</a>, tener a travis como herramienta de ci y otras integraciones que podemos ver en <a href="https://github.com/alexjoverm/typescript-library-starter">la documentación</a>.</p><p>Dijimos que cuando nuestra lógica de negocios aumenta, vamos a querer componer funciones simples para crear funciones más complejas. Para eso vamos a usar <a href="https://ramdajs.com/">ramda</a>, una librería JavaScript que tiene varios utilitarios para hacer programación funcional. Al mismo tiempo, veremos cómo podemos crear una librería que use otra librería.</p><p>Con el siguiente comando instalaremos tanto ramda como sus tipos.</p><pre>$ npm install ramda @types/ramda</pre><p>En el siguiente código haremos un par de cosas. Primero, crearemos una versión currificada de la suma y la multiplicación, lo que significa que podemos llamar a las funciones pasandole ambos parámetros y obtener la solución, o como en este caso, pasarle un argumento y tener la función parcialmente aplicada. Luego crearemos una función más compleja a partir de las funciones más simples usando <strong>compose</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d61cb42bf102a0e8387186f5796302a5/href">https://medium.com/media/d61cb42bf102a0e8387186f5796302a5/href</a></iframe><p>Si miramos al ejemplo desde un IDE como VSCode, podemos ver que la función <em>incAndDuplicate </em>tiene el tipo esperado, una función que dado un número devuelve un número.</p><p>Si esta es la primera vez que ves la función compose, puede parecer contraintuitivo que está definida como <strong>compose(times2, inc)</strong>, pero la función <em>inc</em> es la primera en ser llamada y luego la función <em>times2</em>. Esto viene de la definición matemática de composición, donde (f º g)(x) = f(g(x)). En este ejemplo <strong>f</strong> siendo <em>times2</em> y <strong>g</strong> siendo <em>inc</em>.</p><p>Una vez más, podemos compilar la librería y poner los resultados en <em>bundle.gs</em>. Si miramos de cerca, podemos ver que el archivo ahora contiene nuestro código y el de ramda. Podemos conectarlo con Google Sheet agregando la siguiente función al <em>Code.gs</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec0a7753889e4079a1e01816acfbd051/href">https://medium.com/media/ec0a7753889e4079a1e01816acfbd051/href</a></iframe><p>Vale notar que el argument <em>n</em> no tiene una definición de tipos, al final de cuentas esto es JavaScript/AppScript. Esto nos lleva a la pregunta, cómo se relaciona esto con los tipos definidos en nuestro código TypeScript? Vamos a hablar más de esto en futuros posts.</p><p>Si llamamos a nuestra nueva función desde la planilla usando un número, podemos ver que el resultado es el esperado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*i0n0uCK6X209dFjjuWYPow.png" /></figure><p>Lo lindo de la composición es que ahora podemos crear funciones aún más complejas utilizando las que ya creamos. Para nuestro último paso, creemos una función que sirva para matrices de números.</p><p>Podemos crear una función que reciba un array de arrays de números (una matriz) y que devuelva el mismo tipo. Si usamos <em>map</em> en la matriz, iteraremos sobre las filas, y si hacemos <em>map</em> en las filas iteraremos sobre las celdas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8b402d5f129803b872dccba6184496/href">https://medium.com/media/5c8b402d5f129803b872dccba6184496/href</a></iframe><p>Aunque no hayamos usado la función <strong>compose</strong>, estamos creando nuevas funciones usando las existentes sin modificarlas, y esa es la idea de la programación funcional.</p><p>Si usamos la función <strong>map</strong> definida en ramda podriamos simplificar nuestro código para que sea</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b13ce30ffea135256c1ee7f3c35c24e/href">https://medium.com/media/7b13ce30ffea135256c1ee7f3c35c24e/href</a></iframe><p>Donde <em>incAndDuplicateMatrix2 </em>tiene el tipo correcto para este ejemplo, una función que recibe y devuelve un array de arrays de números. Aclaro que los tipos son correctos para este ejemplo ya que la función <strong>map</strong> en JavaScript también funciona con objetos iterando sobre sus propiedades y cualquier instancia que tenga definido el método map.</p><p>Usando cualquiera de las versiones, el ejemplo funcionará correctamente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*QVjO2BdSMtTqyWx1rwetng.png" /></figure><h3>Buenas noches y segunda cita</h3><p>Hasta ahora vimos porque TypeScript y Google Sheets van bien juntos y una forma simple de integrarlos. Usando el mismo mecanismo podemos integrar cualquier lenguaje que compile a JavaScript. Hace no mucho probé hacerlo con PureScript, que es un lenguaje funcional puro, y los resultados fueron bastante similares.</p><h3>Hernan Rajchert on Twitter</h3><p>Primera prueba exitosa entre PureScript y GoogleSheets ♥️</p><p>Igual prefiero usar TypeScript por la diferencia “ideológica”. PureScript es un leguaje con capacidades distintas a las de JavaScript, y aún si es más idoneo para programar funcionalmente, le agrega una capa de abstracción que dificulta integrar con soluciones JavaScript nativas. TypeScript por el otro lado no intenta ser un lenguaje nuevo, sino una forma de tipar JavaScript. En ese sentido está más cerca del “metal”, si podes llamar metal a JavaScript 😛. Y además, podemos instalar <a href="https://www.npmjs.com/package/@types/google-apps-script">@types/google-app-scripts</a> para usar la API de app scripts en el paradigma que queramos y seguir teniendo la seguridad que nos dan los tipos.</p><p>Por cómo trabaja AppScripts (en el backend), las funciones custom normalmente toman más tiempo que las nativas, esto sería un buen feature para mejorar.</p><p>Para nuestra proxima cita, podemos hablar más de cómo mejorar nuestro workflow usando la herramienta <a href="https://developers.google.com/apps-script/guides/typescript">clasp</a>, ver la diferencia entre los tipos dinámicos y estáticos y cómo se relaciona con Google Sheet, y tal vez cambiar nuestro ejemplo rebuscado de <em>incAndDuplicate </em>por uno más real, como por ejemplo la planilla de balance.</p><p>Eso es todo por ahora! Diganme que les pareció el artículo en twitter <a href="http://www.twitter.com/@sherman3ero">@sherman3ero</a>, todo el feedback es bienvenido❤️.</p><p>Generalmente escribo sobre TypeScript y programación funcional. Por favor diganme los temas que les gustaría leer.</p><p>Saludos 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b96a6d2937b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript meets Google Sheets]]></title>
            <link>https://medium.com/@hernanrajchert/typescript-meets-google-sheets-a4be3891af85?source=rss-9e165ef458c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4be3891af85</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[app-script]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[google-sheets]]></category>
            <dc:creator><![CDATA[Hernan Rajchert]]></dc:creator>
            <pubDate>Fri, 26 Oct 2018 19:29:17 GMT</pubDate>
            <atom:updated>2018-11-12T14:55:45.243Z</atom:updated>
            <content:encoded><![CDATA[<p>I said it <a href="https://youtu.be/DKliwV3QdnU?t=466">once</a>, and I’ll say it again, Google Sheet is an awesome tool to learn some Functional Programming concepts. For example, the fact that we don’t care if a cell is a constant value or the result of a function should scream <a href="https://en.wikipedia.org/wiki/Referential_transparency">referential transparency</a>. Also, the way we do conditional logic resembles more to the ternary operator than the imperative <em>if statement, </em>and that shows us how to construct a program where everything is an expression.</p><p>But is not a bed of roses, Google Sheet functions can’t be <strong>composed</strong> together to form newer richer functions, which is the bread and butter of functional programming. That may leave us with some really large expressions if our logic is complicated. Luckily for us, Google Sheets has an open relationship with AppScript/JavaScript, and on the other side, TypeScript really digs JavaScript, so I thought, the two of them should meet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZa3sk2vrAZNS4JYBrcT-A.png" /></figure><h3>But why</h3><blockquote>Your scientists were so preoccupied with whether or not they could, they didn’t stop to think if they should — Dr. Ian Malcolm, Jurassic Park</blockquote><p>This is a twofold question, first, why use Google Sheets, and second, why extend it with JavaScript/TypeScript.</p><p>Google Sheets is a multi-purpose programming environment with a really low entry point barrier. I’ve personally used to create <a href="https://medium.com/@ms.mbalke/aarrr-framework-metrics-that-let-your-startup-sound-like-a-pirate-ship-e91d4082994b">AARRR funnel reports</a> that help my company make business decisions, personal balance reports to know where I stand financially and most recently a sheet to help me plan for an upcoming bicycle Europe trip 🚲. The main benefit is that we can focus on our data and the business logic behind it, and kind of forget about the UI.</p><p>As I mentioned before, if our logic becomes complex enough we may want to use the power of a full-fledged programming language by creating an <a href="https://en.wikipedia.org/wiki/Google_Apps_Script">App Script</a>, which is a solution introduced to the G-suite back in 2009 and it’s compatible with most features available in <strong>E</strong>cma<strong>S</strong>cript<strong>5</strong>. Currently, in 2018, <strong>ES5</strong> can seem outdated, but luckily for us, we can use a compiler/transpiler such as TypeScript to get some of the latest language features such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring</a>.</p><p>We can also benefit from having a type checker that can warn us if we are doing something wrong. It took me a lot of manual testing to figure out that when we pass a 1 column range of numbers as an argument to AppScript, we are not passing a simple array, rather an array of arrays. The confusing part was due to the way JavaScript coerces values, so my examples worked for some cases and not for others. When using a type checker and correctly typing a range, you could get a warning without even running the code.</p><p>Another benefit is being able to work with your sheets offline. I recently went on a trip to San Luis province in Argentina, where the WIFI is free but the connection quality may vary. I decided to create my balance sheet and I used a TypeScript starter kit that I’ve already had installed on my computer. By using the types, and writing some unit test, I knew the code would work before running it on the actual page 🎉.</p><h3>First date</h3><p>So now that the introductions are made, let’s dim the lights, put some Marvin Gaye and let’s get it on. We’ll start with a simple Hello World.</p><p>Create a new Google Sheet and in the menu select <em>Tools -&gt; Script Editor</em>. A web-based editor will open in a new tab. Write the hello world function, save the project using any name and invoke the newly created function in a cell, just as if it were a native function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rNH7w3r4ZTxmYopV" /><figcaption>Hello World with App Script</figcaption></figure><p>Now that the mood is right, let’s see if we can bring TypeScript to the party. In the <a href="https://developers.google.com/apps-script/guides/typescript">official documentation</a>, there is an example on how to integrate it using the <a href="https://developers.google.com/apps-script/guides/clasp">clasp</a> command tool. But we’ll use @alexjoverm <a href="https://github.com/alexjoverm/typescript-library-starter">TypeScript Library Starter</a> to set up the project, because this is, after all, a library that we’ll use from our program Google Sheet. In following entries we can explore how to modify the starter to upload the results using clasp.</p><p>Open up a terminal and enter the following commands</p><pre>$ git clone <a href="https://github.com/alexjoverm/typescript-library-starter.git">https://github.com/alexjoverm/typescript-library-starter.git</a> ts-integration-test<br>$ cd ts-integration-test<br>$ npm install</pre><p>Follow the instructions, and once installed, use your favourite editor to modify <strong>src/ts-integration-test.ts</strong> to be</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fac339b474ed4c99eef38d7b9906bc5/href">https://medium.com/media/4fac339b474ed4c99eef38d7b9906bc5/href</a></iframe><p>Then we can build the library in the terminal with the command <strong>npm run build</strong>, which will generate a file called <em>dist/ts-integration-test.umd.js</em> with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3cc44e50f8337bfec2cd4adc24a7df0/href">https://medium.com/media/c3cc44e50f8337bfec2cd4adc24a7df0/href</a></iframe><p>That is a <a href="https://github.com/umdjs/umd">Universal Module Definition</a> which is intended to be run in the server using node, in the browsers, and why not, in Google Sheets. If we pay attention to line 4 we’ll get a hint on how we can use this from our example.</p><p>First, inside the <em>Script Editor </em>create a new script file called <em>bundle.gs </em>and copy the contents of the umd file. Then modify our <em>HELLO</em> function to return the result of calling tshello under the tsIntegrationTest namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tNAOxtrO7rK5A6cM" /><figcaption>Hello World with TypeScript</figcaption></figure><p>With this simple steps we created a TypeScript library that can be called from our spreadsheet and has the ability to unit test with <a href="https://jestjs.io/">Jest</a>, do semantic commits with <a href="https://github.com/commitizen/cz-cli">commitizen</a>, have travis as a ci tool and some other integrations that you can see in <a href="https://github.com/alexjoverm/typescript-library-starter">the documentation</a>.</p><p>We said that when our business logic grows, we would like to compose simple functions into more complex ones, for that, we’ll use Ramda, a JavaScript library that has common functional helpers. At the same time, we’ll see how we can create a library that uses another library.</p><p>With the following command, we’ll install both ramda and its types definitions.</p><pre>$ npm install ramda @types/ramda</pre><p>In the following code, we’ll do a couple of things. First, we create a <a href="https://medium.com/@hernanrajchert/creating-typings-for-curry-using-ts-3-x-956da2780bbf">curried </a>version of addition and multiplication, which means that if we can call the function with both arguments we receive the solution, or we can pass one argument and receive a partially applied function. Then we create a more complex function out of the simpler ones using compose. If you look at the code with an IDE such as VSCode you can see that <em>incAndDuplicate</em> has the expected type, a function that given a number returns a number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d61cb42bf102a0e8387186f5796302a5/href">https://medium.com/media/d61cb42bf102a0e8387186f5796302a5/href</a></iframe><p>If this is the first time you use the compose function, it can seem counterintuitive that it’s defined as <strong>compose(times2, inc)</strong>,<strong> </strong>but the <em>inc</em> function is the first one to be applied and then the <em>times2</em>. This comes from the mathematical definition of composition, where (f º g)(x) = f(g(x)). In this case <strong>f</strong> being <em>times2</em> and <strong>g</strong> being <em>inc</em>.</p><p>Once again, we can compile the library and put the results into <em>bundle.gs.</em> If we take a closer look, we’ll see that the file now contains our code and ramdas. We can connect it with Google Sheet by adding the following function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec0a7753889e4079a1e01816acfbd051/href">https://medium.com/media/ec0a7753889e4079a1e01816acfbd051/href</a></iframe><p>Notice that the argument <em>n</em> doesn’t have a type definition, is JavaScript/AppScript after all. So this brings up the question, how does this relate to the types defined in our TypeScript application? we’ll talk more about this in another post.</p><p>If we call our newly composed function from the sheet using a number, we’ll see the expected result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*i0n0uCK6X209dFjjuWYPow.png" /></figure><p>The nice thing about composition is that we can now create even more complex functions out of the existing ones. For our last step, let’s make a new function that works on a matrix of numbers.</p><p>We can create a function that receives an array of arrays of numbers (a Matrix) and returns the same type. By mapping over the range we get each row, and by mapping over the row we get each cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c8b402d5f129803b872dccba6184496/href">https://medium.com/media/5c8b402d5f129803b872dccba6184496/href</a></iframe><p>Even if we didn’t use the <strong>compose </strong>function, we are creating a new function out of the existing one without modifying it, which is the idea of functional programming.</p><p>If we use ramdas <strong>map </strong>function we could simplify the code like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b13ce30ffea135256c1ee7f3c35c24e/href">https://medium.com/media/7b13ce30ffea135256c1ee7f3c35c24e/href</a></iframe><p>Where <em>incAndDuplicateMatrix2</em> has the correct types for this example, a function that receives and returns an array of arrays of numbers. I clarify that the types are correct for this example, as the JavaScript <strong>map </strong>function also works with Objects and any object that has a map function defined.</p><p>Using any of the versions, the example would work as expected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*QVjO2BdSMtTqyWx1rwetng.png" /></figure><h3>Kiss goodnight and second date</h3><p>So far we’ve seen why TypeScript and Google Sheets are a good fit for each other and a simple way to integrate them together. Using the same mechanism we could potentially integrate with any language that compiles to JavaScript. Not so long ago I tried it with PureScript, which is a purely functional language, and the results were very similar.</p><h3>Hernan Rajchert on Twitter</h3><p>Primera prueba exitosa entre PureScript y GoogleSheets ♥️</p><p>I still prefer to use TypeScript because of the difference in principles. PureScript is a new language with different capabilities than JavaScript, and even if it’s more suitable for Functional Programming, it adds a layer of abstraction that makes it a little bit more difficult to integrate with native JavaScript solutions. TypeScript on the other side does not intend to be a new language, rather a way to type JavaScript. In that sense is closer to the “metal”, if you can call JavaScript a metal. And on the plus side, you can install <a href="https://www.npmjs.com/package/@types/google-apps-script">@types/google-app-scripts</a> to use the app scripts API in whatever paradigm you choose and still have type safety.</p><p>Because of how AppScript works (in the backend), the custom functions normally takes more time than the native ones, this would be a really nice feature to improve.</p><p>For our next date, we could talk more about how to improve our workflow using the <a href="https://developers.google.com/apps-script/guides/typescript">clasp tool</a>, the difference between static and dynamic typing, and how it relates to Google Sheet, and maybe change the contrived <em>incAndDuplicate</em> example for a real case usage such as the balance sheet.</p><p>That’s it for now! Let me know what you think of the article on twitter <a href="http://www.twitter.com/@sherman3ero">@sherman3ero</a>, all feedback is welcomed ❤️.</p><p>I generally write about TypeScript and functional programming. Please tell me what topics would you like to read about.</p><p>Cheers 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4be3891af85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guardians of the code]]></title>
            <link>https://medium.com/@hernanrajchert/guardians-of-the-code-ec0e3d3bc06a?source=rss-9e165ef458c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0e3d3bc06a</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hernan Rajchert]]></dc:creator>
            <pubDate>Fri, 07 Sep 2018 19:58:01 GMT</pubDate>
            <atom:updated>2018-09-10T23:00:27.677Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers, we don’t want to spend our sprint time hunting bugs, and we don’t want to be called at 8 pm on a Saturday night because our software is behaving strangely. We want to have confidence in what we do, we need a hero that <strong>guards </strong>us and protect us from making mistakes that could have been easily avoided. We need to start programming more defensively! We need… Contracts???</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Ke0Nfo5y09Ch8Kq0RANzzQ.gif" /><figcaption>Unexpected behaviour can cause some serious bugs</figcaption></figure><h4>Contracts to the rescue!</h4><p>Every time we program we define contracts, even if we don’t do it consciously when we define a function we define a contract stating the parameters it can receive and the relations and restrictions they may have. When we call a function, we are agreeing to its Terms and Conditions, and if its 3rd party code the contract will normally be defined in the form of documentation.</p><p>JavaScript <em>Array.indexOf </em>method is an excellent example. As described in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf">documentation</a> we can use it to search if an element exists in the Array. It has two possible arguments, the first one is <strong>mandatory</strong>, and the other one is <em>optional</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEDXQ_pN8adi3jvtQP-8jg.png" /><figcaption>JavaScript array’s indexOf method</figcaption></figure><p>It’s worth noting all the conditions that relate to the second argument. What happens if we don’t pass it? What happens if it’s a negative number? What happens if it’s a number greater than the size of the Array? What happens if we make a mistake and pass a string?</p><p>If we were to program such a function ourself, we would probably do something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d935a1a4fdb62a32350fa9c3b6bc1476/href">https://medium.com/media/d935a1a4fdb62a32350fa9c3b6bc1476/href</a></iframe><p>Where we define <strong>pre-conditions</strong> that our parameters must comply before doing the actual work. These <strong>pre-conditions</strong> are also known as <strong>Guards</strong>, as taken from the <a href="https://en.wikipedia.org/wiki/Guard_(computer_science)">Wikipedia definition</a>:</p><blockquote>In computer programming, a <strong>guard</strong> is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. Regardless of which programming language is used, <strong>guard code</strong> or a <strong>guard clause</strong> is a check of integrity preconditions used to avoid errors during execution.</blockquote><p>To strengthen our contracts we could also define <strong>post-conditions</strong>, that as its name implies are executed after the actual code runs. In the case of <em>indexOf </em>we could assert that the response is a number lower than the size of the array or the number -1.</p><p>Both <strong>pre</strong> and <strong>post</strong> conditions give us guarantees about how we program. The first protects the function from outside calls and the second protects the function from itself.</p><h4>TypeScript For The Win</h4><p>One of the benefits of using <strong>guards </strong>is that they follow the <a href="https://enterprisecraftsmanship.com/2015/09/15/fail-fast-principle/">fail fast principle</a>. Instead of letting the error propagate or be swallowed, they warn you as soon as they see a mistake and help you pinpoint the origin.</p><p>To fail even faster, we can use a <strong>static type checker </strong>such as TypeScript. It works as the police of our programs, allowing us to enforce the contracts we write at compile time. In the following example we refactored one of the <strong>pre-conditions</strong> by adding type annotations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc6ecbb5a6f7308de19e5c3559afa150/href">https://medium.com/media/dc6ecbb5a6f7308de19e5c3559afa150/href</a></iframe><p>If we call our function and we don’t adhere to its contract, it will fail at compile time, which means faster development cycles as we don’t even need to try the code, the compiler will point us in the right direction.</p><p>Our mental complexity has clearly gone up as generics are more complicated than a simple <em>if statement, </em>but we gain more guarantees. A question that we didn’t asked before is: what happens if we have a list of numbers <strong>[1, 2, 3]</strong> and we search for a string, for example <strong>“3”</strong>? The answer is probably what you expect, we receive a -1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10706e3dd3a38eb19ff963e4abc404b/href">https://medium.com/media/f10706e3dd3a38eb19ff963e4abc404b/href</a></iframe><p>If we don’t use a type checker, <em>indexOf’s</em> contract will silently swallow a bug. By using TypeScript we’ll get an error that makes us ask the right question: why were we looking for a string in an array of numbers in the first place?</p><p>We can also add a return type to our function to act as a <strong>post-condition</strong>,<strong> </strong>enforcing us to return a number. But you should know that<em> not all type systems are created equal </em>and they may give you different guarantees. For example, TypeScript <strong>can’t</strong> enforce you to return a number in the correct range, while other more restrictive languages such as <a href="https://www.idris-lang.org/">IDRIS</a> could.</p><h4>Type guards</h4><p>TypeScript has a concept called <em>Type Guards</em> that is related to what we talked so far, but instead of <em>continuing or not the program execution</em>, it will narrow the type of a variable in a scope depending on some dynamic checks.</p><p>Let’s consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4d67a3127b62add4cbe1be725ce334/href">https://medium.com/media/ce4d67a3127b62add4cbe1be725ce334/href</a></iframe><p>If we run it in the JavaScript console and the element exists, everything will be ok, but if it doesn’t we’ll get the <strong>runtime</strong> <strong>error</strong>: <em>Cannot set property ‘innerHTML’ of null.</em></p><p>If we use the TypeScript compiler with the <em>strictNullCheck </em>option enabled, the function <em>getElementById</em> will return the <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types">union type</a> “<em>HTMLElement | null</em>”. So it doesn’t matter if the element exists or not, we’ll get a <strong>compile time error </strong>saying that the object may be null.</p><p>By adding a simple clause we fix the error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e0a47587cedf639450b92058224254/href">https://medium.com/media/f2e0a47587cedf639450b92058224254/href</a></iframe><p>This is possible thanks to <strong>Type Guards.</strong> TypeScript uses code flow analysis to try to understand all the possible types a variable can have in different parts of the code. In the first line, <em>header </em>can be “<em>HTMLElement | null</em>”, the only way to get to line 4 is if <em>header</em> is thrutly, so TypeScript will narrow its type to <em>HTMLElement. Similarly</em>, the only way to get to line 6 is if header is falsy, so the type will be <em>null</em>.</p><p>Type Guards can also be used to define <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">algebraic data types</a> (ADT) to separate logic from data. Let’s examine the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47c9bcd0953244b086affc521208f7c/href">https://medium.com/media/a47c9bcd0953244b086affc521208f7c/href</a></iframe><p>Inside the function <em>doYourThing </em>we don’t know too much about animal. We know it has a property called <em>species</em> as both <em>Cat</em> and <em>Dog</em> have a property with that name. The type of the property will be the union of the possible types, in this case <em>‘cat’ | ‘dog’.</em></p><p>The only way to reach line 19 is if <em>species </em>equals to <em>‘dog’, </em>so the Type Guard will narrow animal’s type to <em>Dog</em> in that block, allowing us to use the property <em>favoriteHuman</em>. Similarly, if we reach line 21 is because <em>animal</em> is of type <em>Cat </em>thus will have the property <em>nemesis</em>.</p><p>We shouldn’t be able to reach line 23 because <em>species</em> can only be <em>‘cat’</em> or <em>‘dog’ </em>and both conditions were checked inside the function, so the Type Guard concludes that in that block <em>animal</em> type is <strong>never</strong>. This allows us to do something called exhaustiveness checking, a pattern that enforces us to check all possible values in the ADT. If we add a new <em>Animal</em> in line 11 and we don’t modify our function, we’ll get an error because we cant pass it to assertNever.</p><p>You can see a live demo in <a href="https://youtu.be/d1f6VBmWg6o?t=42m1s">this talk</a> by <a href="https://twitter.com/ahejlsberg">Anders Hejlsberg</a>, a core developer of the language.</p><h4>Custom Type Guards</h4><p>TypeScript comes with a variaty of Type Guards already predefined. We have <em>instanceOf</em>, <em>typeOf, </em>and <em>literal values </em>out of the box, but there are scenarios where we need to define our own Guards.</p><p>The concept that we used in the previous section to create our ADT’s is called <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions">discriminated unions</a>, where we take advantage that all the types in the union share a common property. But what happens if the types are not that homogeneous.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/551eec1c5c0119471ddb24e98b2ac624/href">https://medium.com/media/551eec1c5c0119471ddb24e98b2ac624/href</a></iframe><p>This code will throw an error at compile time on line <em>15</em>, as TypeScript can’t assume that <em>feline </em>has a property called <em>species. </em>If we try to hint the compiler by casting to <em>Cat</em>, we’ll break the Type Guard and cause an error on the <em>assertNever</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3caa8fc38c5c6f4fce1fa69a45c2d43/href">https://medium.com/media/f3caa8fc38c5c6f4fce1fa69a45c2d43/href</a></iframe><p>To make this example work, we need to create a custom Type Guard, which is nothing more than a function that returns a boolean. The syntax is quite easy, you receive a parameter <strong>x</strong> with some general type and return a type <strong>x is foo </strong>to indicate that if the condition is true then <strong>x </strong>is of type <strong>foo</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/470cffb99921bccecb4df86d2b5a5f25/href">https://medium.com/media/470cffb99921bccecb4df86d2b5a5f25/href</a></iframe><p>And now our example works just fine 👍. If you want to see a real example of custom type guards, you can check how we use the <a href="https://github.com/ts-task/utils#isinstanceof">variadic isInstanceOf</a> and <a href="https://github.com/ts-task/utils#caseerror">caseError</a> to correctly manage our errors using <a href="https://github.com/ts-task/task">Task</a>.</p><p>That’s it for now! Let me know what you think of the article on twitter <a href="http://www.twitter.com/@sherman3ero">@sherman3ero</a>, all feedback is welcomed ❤️.</p><p>I generally write about TypeScript and functional programming. Please tell me what topics would you like to read about.</p><p>Cheers 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0e3d3bc06a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Literal types to the test]]></title>
            <link>https://medium.com/@hernanrajchert/literal-types-to-the-test-fb989d2d0c4a?source=rss-9e165ef458c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb989d2d0c4a</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hernan Rajchert]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 03:13:05 GMT</pubDate>
            <atom:updated>2018-08-20T03:13:05.944Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>We use TypeScript because we want to restrict how we program, with the idea that those restrictions will make us write safer code. On that path, we can find a feature of the language called <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types">literal types</a>, which will enable us to fasten the seatbelt a little bit more.</p><p>This feature can have some quirks related to type inference, so in this post we’ll investigate it using <a href="https://github.com/Microsoft/dtslint">dtslint</a>, a very powerful tool created by Microsoft that allows us to test our types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lF0GeRgCcLFPBxRLm5EAtg.gif" /></figure><h4>What are literal types?</h4><p>We can think about our types as Sets, meaning <strong>string</strong> includes all possible strings, <strong>number</strong> all numbers, <strong>booleans</strong> are <em>true</em> or <em>false</em>. A literal type is just one element of the Set, that allow us (in conjunction with <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#union-types">union types</a>) to define subsets with special meaning. For example, we can model the type of a dice 🎲 or some CSS property like <a href="https://www.w3schools.com/cssref/css3_pr_flex-grow.asp">flex-grow</a> 👨‍🎨.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*tKOEIT-gXzJjICHidOrHcA.png" /></figure><p>By doing this, we are restricting our programs a little bit more, as a dice can be assigned to a number but not the other way around.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84c9ddcd248ebc49a61eb2a75cbf63c4/href">https://medium.com/media/84c9ddcd248ebc49a61eb2a75cbf63c4/href</a></iframe><p>Another great use of literal types is that they enable us to write in a functional way by using the <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions">discriminated unions</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f616f5ed704184bbd5bcc0efc609e998/href">https://medium.com/media/f616f5ed704184bbd5bcc0efc609e998/href</a></iframe><p>But I let <a href="https://twitter.com/ahejlsberg">Anders Hejlsberg</a>, a core developer of the language, explain it with more detail in <a href="https://youtu.be/d1f6VBmWg6o?t=42m1s">this video</a>.</p><h4>Types to the test</h4><p>Literal types are not straightforward when dealing with type inference, so we’ll use <a href="https://github.com/Microsoft/dtslint">dtslint</a> to help with the investigation. This is a tool made by Microsoft that in my opinion has some great potential but it’s currently underrated.</p><p>With the help of <a href="https://hackernoon.com/testing-types-an-introduction-to-dtslint-b178f9b18ac8">this post</a> and <a href="http://koerbitz.me/posts/unit-testing-typescript-types-with-dtslint.html">this post</a>, we can set up <a href="https://github.com/hrajchert/literal-ts-blog">a project</a> that allows us to make some basic assertions about the inferred types.</p><p>For example, we can check the following case: When we initialize a <em>variable</em> with <strong><em>“foo”</em> </strong>the inferred type is <strong><em>string</em></strong>, but when we set a <em>constant</em> TypeScript can be more specific and infer the literal type (because it knows that the value won’t change).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad4337e15c8242e2fa82224f5fb62771/href">https://medium.com/media/ad4337e15c8242e2fa82224f5fb62771/href</a></iframe><p>By writing <em>// $ExpectType “foo” we </em>can assert what’s the inferred type of an identifier, so it also works like a unit test for types.</p><p>We could’ve checked this just by hovering the identifiers in vscode or in this <a href="https://www.typescriptlang.org/play/#src=const%20literalFoo%20%3D%20&#39;foo&#39;%3B%0D%0Alet%20stringFoo%20%3D%20&#39;foo&#39;%3B%0D%0A">typescript playground</a>, but dtslint gives us one advantage, it can check against all TypeScript versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FeuFCVqlvcP1cFsHF3T1jw.png" /></figure><p>This tells us that even if the <em>string literal types</em><strong> </strong>were introduced in version 1.8, this inference optimization was available at 2.1. 🕵🏻‍</p><h4>Where the inference gets tricky</h4><p>It’s normal to have a function that returns a <em>discriminated union </em>type like the one defined earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d87e1960ed2445386b8a9ac4b1daa1b4/href">https://medium.com/media/d87e1960ed2445386b8a9ac4b1daa1b4/href</a></iframe><p>This example infers as you expect, and protects you properly by giving you an error if you misspell a property name (e.g. <em>nemessis</em> instead of <em>nemesis</em>), if use a <strong><em>type</em> </strong>other than <strong><em>“cat”</em></strong> or <strong><em>“dog”</em></strong><em>,</em> etc.</p><p>This works as expected in all versions of TypeScript after 2.1, but you can notice how they’ve <a href="https://github.com/Microsoft/TypeScript/issues/25310">improved the error messages</a> in version 3.0 🎉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qSCQ9LmZLOCXfXngtNOWw.jpeg" /><figcaption>TS 2.5 on the left, 3.0 on the right.</figcaption></figure><p>If we add an extra layer of indirection, the inference doesn’t work as well. For example, the following code should be correct but the compiler will fail along the lines of: <em>Type </em><strong><em>string</em></strong><em> is not assignable to type </em><strong><em>‘cat’</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc08be920d278334301c08ccd83afa95/href">https://medium.com/media/bc08be920d278334301c08ccd83afa95/href</a></iframe><p>The inference of the <strong><em>result</em></strong> identifier varies between TypeScript versions, but they all have one thing in common, the property <strong><em>type </em></strong>is inferred to be a<strong><em> string. </em></strong>So when we try to return that object we get an error of <strong><em>string</em></strong> not being assignable to <strong><em>‘cat’</em></strong>. Using dtslint we can see that the error starts at <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html">version 2.4</a>, most likely because of the strict covariance checks.</p><p>So we need to find a way to let the compiler know that the property <strong><em>type </em></strong>is not just any string. The first solution is to interpret the whole object literal as one of the interfaces we defined, that way TypeScript knows that the first <strong><em>type</em></strong> should be <strong><em>‘cat’ </em></strong>and that it also has to have a <strong><em>nemesis </em></strong>property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f860e9a299feb32e7c90ecf65508efd/href">https://medium.com/media/7f860e9a299feb32e7c90ecf65508efd/href</a></iframe><p>Another way is to cast the string<strong> </strong>as the literal type, but it looks kind of weird.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77af926bd1bfaa6fb6ce0d1adce349a1/href">https://medium.com/media/77af926bd1bfaa6fb6ce0d1adce349a1/href</a></iframe><p>The first version is a little bit better when something goes wrong because it can compartmentalize the error. Instead of having to check that both <em>return objects</em> are compatible with the type of the promise, it first checks that each <em>object literal</em> is compatible with the provided interface and that the provided interface is assignable to the type of the promise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5ofck9T05bXfCutL3mSBQ.jpeg" /></figure><p>The last thing we can do to help the compiler is to reduce the indirection level whenever possible. In the following example, instead of typing the return of the function I’m manually passing the type to the <strong><em>Promise</em></strong> constructor, that way, the inner function works like our first <em>createAnimal </em>example and the outer function just infers what we return, a Promise of an Animal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1641a75175bf49f12c305b751181c92/href">https://medium.com/media/f1641a75175bf49f12c305b751181c92/href</a></iframe><h4>Another way to cast a literal type</h4><p>By using the <em>extends</em> restriction of a <em>generic type </em>we can write an identity function that does nothing to the value, and whose only purpose is to cast the value as the literal type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4bd9c1b1b4d11dfddaf2fa9d4170e37/href">https://medium.com/media/c4bd9c1b1b4d11dfddaf2fa9d4170e37/href</a></iframe><p>This allow us to replace <strong><em>‘cat’ as ‘cat’</em></strong> with <strong><em>lit(‘cat’)</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d09e4cfdd147b173dddac2b20eb8b7b4/href">https://medium.com/media/d09e4cfdd147b173dddac2b20eb8b7b4/href</a></iframe><p>Even if in this particular case, casting the string as the literal type is not “the best” in terms of error messages, It’s still a technique that could prove useful. And once again, by using <a href="https://github.com/Microsoft/dtslint">dtslint</a> we know that it only works on version 2.9 forward.</p><p>All this makes me think that as library authors we should be using dtslint to test our types because it let us know when to use certain language features and to test our functions for different inference scenarios.</p><p>That’s it for now! Let me know what you think of the article on twitter <a href="http://www.twitter.com/@sherman3ero">@sherman3ero</a>, all feedback is welcomed ❤️.</p><p>I generally write about TypeScript and functional programming. Please tell me what topics would you like to read about.</p><p>Cheers 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb989d2d0c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating typings for curry using TS 3.x]]></title>
            <link>https://medium.com/@hernanrajchert/creating-typings-for-curry-using-ts-3-x-956da2780bbf?source=rss-9e165ef458c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/956da2780bbf</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Hernan Rajchert]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 14:48:21 GMT</pubDate>
            <atom:updated>2018-08-08T01:05:53.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Compose all the things 🎉</h3><p>Functional Programming is all about composing functions together and that means we need to make the output of a function to serve as the input of the next one. In order to do so, it’s convinient to make functions have a similar “shape”, thats why in lambda calculus all functions are <em>1-ary</em>, meaning they all receive one argument and return one value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*TrLK-qfUz9BtTWE5ZB2XaA.jpeg" /></figure><p>In modern JavaScript you can achieve that by using arrow functions and passing one parameter at a time, but we lose the ability to call our function with all the parameters at once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7993a65a5cf7213470aaad321389a1b3/href">https://medium.com/media/7993a65a5cf7213470aaad321389a1b3/href</a></iframe><p>Thats when curry-ing comes in handy as it lets you define your function with all the parameters at once and then call them however you like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8037bfba2538403255cc95c8c4b0912/href">https://medium.com/media/d8037bfba2538403255cc95c8c4b0912/href</a></iframe><p>Purely functional languages such as Haskell, Elm or Purescript have curry-ing built-in at it’s core, but in JavaScript we need to use a library such as ramda or make our own function.</p><p>If you just want to use curried functions in TypeScript and have the type checker to correctly know what’s what, I recommend you install <em>ramda</em> and <em>@types/ramda </em>with npm. This post is ment to learn how to create typings for a generic curry function and in the process learn some of the advanced features of TypeScript such as <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html">conditional types</a>, <a href="https://blogs.msdn.microsoft.com/typescript/2018/07/30/announcing-typescript-3-0/#richer-tuple-types">richer tuple types</a> and <a href="https://blog.mariusschulz.com/2016/08/18/function-overloads-in-typescript">function overloads</a>.</p><p>If you want to see the full example, here is a <a href="https://github.com/hrajchert/ts-curry-example">link to the repo</a>.</p><h3>Function overload</h3><p>To create the typings for a generic curry function we’ll start by creating a simple concrete curried function and work our way up.</p><p>So we are going to try to curry the <strong>add</strong> function, wich takes two numbers and adds them together. In order to do this, we’ll use <a href="https://blog.mariusschulz.com/2016/08/18/function-overloads-in-typescript">function overloads</a> which is a mechanism to provide different call signatures for the same function.</p><p>The following type declarations says that if we call <strong>add</strong> with two numbers it will return us the addition, but if we only pass one argument, it will return us a new function, that receives the second number and returns the addition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/007456fc0db30d28bcc69f0a8298d162/href">https://medium.com/media/007456fc0db30d28bcc69f0a8298d162/href</a></iframe><p>Notice that we have three lines with the <strong>add</strong> function, the first two are the <a href="https://blog.mariusschulz.com/2016/08/18/function-overloads-in-typescript">function overloads</a>, which specifies the different ways the function can be called, and ends with a “<strong>;</strong>”.<strong> </strong>The third <strong>add</strong> is the implementation of all the overloaded functions, and as such, the type must be generic enough to contemplate all the cases.</p><p>The last line is not actually needed to create the <strong>add</strong> function but it’s there to help us understand a different way to describe overloaded functions. If you hover over <strong>OverloadedAdd</strong> in the <a href="https://www.typescriptlang.org/play/#src=function%20add(a%3A%20number%2C%20b%3A%20number)%3A%20number%3B%0D%0Afunction%20add(a%3A%20number)%3A%20(b%3A%20number)%20%3D%3E%20number%3B%0D%0Afunction%20add(...args%3A%20any%5B%5D)%3A%20any%20%7B%0D%0A%20%20%20%20%2F%2F%20We%20don&#39;t%20care%20about%20the%20implementation%20for%20now%0D%0A%20%20%20%20return%20null%20as%20any%3B%0D%0A%7D%0D%0A%0D%0Atype%20OverloadedAdd%20%3D%20typeof%20add%3B">playground</a> you’ll see that we can describe a curried function of two arguments like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5f7f8fc7714c7e5a0db70bcd13e0e3b/href">https://medium.com/media/a5f7f8fc7714c7e5a0db70bcd13e0e3b/href</a></iframe><p>Where we assume the functions <strong>add</strong>, <strong>mul </strong>and<strong> div</strong> are defined somewhere as plain JavaScript curried functions (for example using ramda’s or lodash curry) and in here we are only defining it’s type.</p><p>With a little refactoring we can extract <strong>Curry1</strong> as the base case, an <em>1-ary </em>function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/047737cb50a227bbb6ee1490f6dd2edc/href">https://medium.com/media/047737cb50a227bbb6ee1490f6dd2edc/href</a></iframe><p>And from here we can define to the <em>n-th </em>that we want</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ec43ec51ad4d3cc9080c913087e48d/href">https://medium.com/media/65ec43ec51ad4d3cc9080c913087e48d/href</a></iframe><p>This means that if we have a curried function named <strong>bar</strong> that accepts three arguments we can type it using <strong>Curry3. </strong>This will make <strong>bar</strong> to be overloaded with 3 different call signatures (with one, two or three parameters). If we call <strong>bar(1) </strong>we’ll get a <strong>Curry2</strong> function, because there are still two ways we can pass the remaining arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50179461634741e579270589e14d1700/href">https://medium.com/media/50179461634741e579270589e14d1700/href</a></iframe><h3><strong>Unknown number of arguments</strong></h3><p>So far we can type curried functions of <em>n-th</em> arguments (we only defined <em>4-th</em>, but you get the idea), but the <strong>curry</strong> function must work with functions of any lenght, so we must have a way to indicate TypeScript which <strong>CurryN</strong> type to use, we need <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html">conditional typings</a>.</p><p><a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html">Conditional typings</a> is a feature added in version 2.8 of TypeScript, and they allow us to set a type depending on a condition. It works like the ternary operator but with types. In the following example we can notice that the type of <strong>x</strong> will depend on whether <strong>TypeX</strong> matchs or not with <strong>SomeShape</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0095c2c50c2c5e57167ce533d55a37dc/href">https://medium.com/media/0095c2c50c2c5e57167ce533d55a37dc/href</a></iframe><p>So in our case we’ll define a conditional type called <strong>VariadicCurry</strong> which will help us determine which <strong>CurryN</strong> type to use. The name comes from <a href="https://en.wikipedia.org/wiki/Variadic_function">Variadic Functions</a> which are functions that can receive a variable number of arguments. It works by nesting the type condition, so if <strong>T </strong>is a tuple of four numbers it will return a <strong>Curry4</strong> type, if its a tuple of three, <strong>Curry3</strong>, and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab5dfdd3a5dba01562d4f13ba6ded77/href">https://medium.com/media/5ab5dfdd3a5dba01562d4f13ba6ded77/href</a></iframe><p>If the type <strong>T</strong> doesn’t match with any of the tuples, we return the new <a href="https://blogs.msdn.microsoft.com/typescript/2018/07/30/announcing-typescript-3-0/#the-unknown-type">unknown type</a> introduced in TypeScript 3, wich is similar to <strong>any</strong>, but safer in the way that you can’t assign it to every variable, you need to cast it, and ideally after checking it’s type dynamically.</p><p>Now we have all the tools to define our curry function 🎉.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa19ed79c7cd47ec548c318ce662aa79/href">https://medium.com/media/fa19ed79c7cd47ec548c318ce662aa79/href</a></iframe><p>There is a lot going so lets break it in pieces. The function <strong>curry </strong>accepts only one argument named <strong>fn</strong>, which is the function to be curried. The return of <strong>curry </strong>will be of type <strong>CurryN </strong>depending on wheter <strong>T</strong> is a <em>1-tuple</em>, <em>2-tuple</em>, etc. We know <strong>T</strong> will be an <em>n-tuple</em> because we defined it inside the angle brackets <em>&lt;T extends number[]&gt;. </em>And we define that <strong>fn</strong> will be a function of <em>n-th </em>arguments (defined by <em>…args: T</em>) that returns a number.</p><p>The last part is possible thanks to another set of features added in version 3, which allows you to <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#tuples-in-rest-parameters-and-spread-expressions">interact with function parameter lists as tuple types</a>.</p><p>With all this in place we have defined the types for our curry function… that only works with numbers. ¯\_(ツ)_/¯️</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871241dd4d4b9a8118a0f38c884e482f/href">https://medium.com/media/871241dd4d4b9a8118a0f38c884e482f/href</a></iframe><h3>Generic parameters</h3><p>Numbers are great, but we made it this far, lets try to make the function work with all types. We’ll start by making the the return type generic on <strong>R</strong>. We’ll refactor our code making <strong>fn</strong> return a type we know nothing about called <strong>R</strong>. This type propagates all the way trough our other definitions, making each <strong>CurryN</strong> generic on the return type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7b6cbd8678b911b18aad7ceff7e0ee7/href">https://medium.com/media/b7b6cbd8678b911b18aad7ceff7e0ee7/href</a></iframe><p>Making all <strong>CurryN</strong> generic in their arguments its fairly easy as well, we just have to make our types to accept extra parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/574b6544dad14210b774ae2c23bfedba/href">https://medium.com/media/574b6544dad14210b774ae2c23bfedba/href</a></iframe><p>And to make <strong>VariadicCurry</strong> and <strong>curry</strong> to use the new parameters we need to do one more “trick”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04be096a724c6762a23be778e4592af2/href">https://medium.com/media/04be096a724c6762a23be778e4592af2/href</a></iframe><p>The <strong>VariadicCurry</strong> type will now match <strong>T</strong> to a <em>n-tuple</em> ignoring the argument type (because we use <strong>any </strong>instead of<strong> number</strong>) and only caring about the <em>arity </em>of the tuple. When we return a specific <strong>CurryN</strong> we use the indexed types <em>T[0], T[1], T[2] and T[3] </em>to specify the correct arguments types.</p><p>And that’s it! We now have the typings for a <strong>curry</strong> function that works with an unknown number of arguments and any type you may think. If you want to try the full code you can browse <a href="https://github.com/hrajchert/ts-curry-example">this repo</a> or use <a href="https://www.typescriptlang.org/play/#src=type%20Curry1%3CA%2C%20R%3E%20%3D%20(a%3A%20A)%20%3D%3E%20R%3B%0D%0A%0D%0Atype%20Curry2%3CA%2C%20B%2C%20R%3E%20%3D%20%7B%0D%0A%20%20%20%20(a%3A%20A)%3A%20Curry1%3CB%2C%20R%3E%3B%0D%0A%20%20%20%20(a%3A%20A%2C%20b%3A%20B)%3A%20R%3B%0D%0A%7D%3B%0D%0A%0D%0Atype%20Curry3%3CA%2C%20B%2C%20C%2C%20R%3E%20%3D%20%7B%0D%0A%20%20%20%20(a%3A%20A)%3A%20Curry2%3CB%2C%20C%2C%20R%3E%3B%0D%0A%20%20%20%20(a%3A%20A%2C%20b%3A%20B)%3A%20Curry1%3CC%2C%20R%3E%3B%0D%0A%20%20%20%20(a%3A%20A%2C%20b%3A%20B%2C%20c%3A%20C)%3A%20R%3B%0D%0A%7D%3B%0D%0A%0D%0Atype%20Curry4%3CA%2C%20B%2C%20C%2C%20D%2C%20R%3E%20%3D%20%7B%0D%0A%20%20%20%20(a%3A%20A)%3A%20Curry3%3CB%2C%20C%2C%20D%2C%20R%3E%3B%0D%0A%20%20%20%20(a%3A%20A%2C%20b%3A%20B)%3A%20Curry2%3CC%2C%20D%2C%20R%3E%3B%0D%0A%20%20%20%20(a%3A%20A%2C%20b%3A%20B%2C%20c%3A%20C)%3A%20Curry1%3CD%2C%20R%3E%3B%0D%0A%20%20%20%20(a%3A%20A%2C%20b%3A%20B%2C%20c%3A%20C%2C%20d%3A%20D)%3A%20R%3B%0D%0A%7D%3B%0D%0A%0D%0Atype%20VariadicCurry%3CT%2C%20R%3E%20%3D%0D%0A%20%20%20%20T%20extends%20%5Bany%2C%20any%2C%20any%2C%20any%5D%20%3F%20Curry4%3CT%5B0%5D%2C%20T%5B1%5D%2C%20T%5B2%5D%2C%20T%5B3%5D%2C%20R%3E%20%3A%0D%0A%20%20%20%20T%20extends%20%5Bany%2C%20any%2C%20any%5D%20%3F%20Curry3%3CT%5B0%5D%2C%20T%5B1%5D%2C%20T%5B2%5D%2C%20R%3E%20%3A%0D%0A%20%20%20%20T%20extends%20%5Bany%2C%20any%5D%20%3F%20Curry2%3CT%5B0%5D%2C%20T%5B1%5D%2C%20R%3E%20%3A%0D%0A%20%20%20%20T%20extends%20%5Bany%5D%20%3F%20Curry1%3CT%5B0%5D%2C%20R%3E%20%3A%0D%0A%20%20%20%20unknown%0D%0A%3B%0D%0A%0D%0Adeclare%20function%20curry%3CT%20extends%20any%5B%5D%2C%20R%3E%0D%0A%20%20%20%20(fn%3A%20(...args%3A%20T)%20%3D%3E%20R)%3A%20VariadicCurry%3CT%2C%20R%3E%3B%0D%0A%0D%0A%0D%0A%0D%0Aconst%20print4%20%3D%20curry(%0D%0A%20%20%20%20(a%3A%20number%2C%20b%3A%20string%2C%20c%3A%20boolean%2C%20d%3A%20number%5B%5D)%20%3D%3E%20%60a%3A%20%24%7Ba%7D%20b%3A%20%24%7Bb%7D%20c%3A%20%24%7Bc%7D%20d%3A%20%24%7Bd%7D%60%0D%0A)%3B%0D%0A%0D%0Aprint4(1)(&#39;hello&#39;)(true)(%5B9%2C%208%5D)%3B%0D%0Aprint4(1%2C%20&#39;hello&#39;%2C%20true%2C%20%5B9%2C%208%5D)%3B%0D%0Aprint4(&#39;hello&#39;%2C%20&#39;hello&#39;%2C%20true%2C%20%5B9%2C%208%5D)%3B">this playground</a>.</p><p>If you like this post send love ❤️, all feedback is welcomed. You can follow me on twitter as <a href="http://www.twitter.com/@sherman3ero">@sherman3ero</a> for more information on TypeScript and functional programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=956da2780bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>