<?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 Roberto Tatasciore on Medium]]></title>
        <description><![CDATA[Stories by Roberto Tatasciore on Medium]]></description>
        <link>https://medium.com/@taitasciore?source=rss-dc7c199417c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GHhND__ArvkpQTmjghynOw.jpeg</url>
            <title>Stories by Roberto Tatasciore on Medium</title>
            <link>https://medium.com/@taitasciore?source=rss-dc7c199417c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:38:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taitasciore/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[Panning With And Without Snapping Using Reanimated 2 And Gesture Handler 2]]></title>
            <link>https://medium.com/@taitasciore/panning-with-and-without-snapping-with-reanimated-2-and-gesture-handler-2-47da8d629280?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/47da8d629280</guid>
            <category><![CDATA[reanimated]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[gesture-handler]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 13:03:10 GMT</pubDate>
            <atom:updated>2023-02-11T10:24:08.684Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to handle simple pan gestures using <a href="https://docs.swmansion.com/react-native-reanimated/">React Native Reanimated 2</a> and <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/">React Native Gesture Handler 2</a> together.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*h_IW8fFxkP3c6uL1qaBeKQ.png" /><figcaption>Software Mansion: the people behind Reanimated and RNGH</figcaption></figure><p>In this article, we will be exploring the basics of working with simple pan gestures with Reanimated 2 and Gesture Handler 2 inspired by and building upon <a href="https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/events#using-context">one of the examples from the Reanimated docs.</a></p><p>This is what we will be building today:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*cv06uDjNmc5BTgXlHhngEg.gif" /></figure><blockquote>The full source can be found here: <a href="https://github.com/phanghos/PanningExample">https://github.com/phanghos/PanningExample</a></blockquote><p>You probably already know how to implement such behaviour with RNGH old v1 API using <em>gesture handlers</em>, since there is an <a href="https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/events/#using-context">example on their documentation.</a></p><p>However, in the interest of always being up to date and working with the latest APIs and versions of libraries, it may not be clear how to implement the same functionality using the new v2 API which relies on the GestureDetector component instead.</p><h4>Installation And Setup</h4><p>First things first, we start by installing both libraries.</p><ul><li>For npm:</li></ul><p>npm i react-native-reanimated react-native-gesture-handler</p><ul><li>For yarn:</li></ul><p>yarn add react-native-reanimated react-native-gesture-handler</p><p>Then, go to the ios directory and install the <em>pod dependencies</em> with pod install</p><p>Finally, make sure to go through the installation guide of both libraries:</p><blockquote>React Native Reanimated: <a href="https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation">https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation</a></blockquote><blockquote>React Native Gesture Handler: <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/installation">https://docs.swmansion.com/react-native-gesture-handler/docs/installation</a></blockquote><h4>Implementation Using RNGH v1 API (With Snapping)</h4><p>After setting up both libraries, we proceed by defining our initial component, a simple circle centered on the screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8e3ef503277734e243d09d5a9784e9/href">https://medium.com/media/3d8e3ef503277734e243d09d5a9784e9/href</a></iframe><p>Since we will be working with animated styles created with the <strong>useAnimatedStyle</strong> Hook to map <em>shared values </em>to styles, we need to use the View component exported from Reanimated instead of the regular one that comes built-in with react-native ; so go ahead and import Reanimated with import Animated from &#39;react-native-reanimated&#39; and replace the innermost View (the circle) with Animated.View : &lt;Animated.View style={styles.circle} /&gt;</p><p>We then proceed to:</p><ul><li>Define our <em>shared values</em> for both <em>x</em> and <em>y, </em>the pressed state of the view, and its scale.</li><li>Define the pan gesture handler with the <strong>useAnimatedGestureHandler</strong> Hook</li><li>Define the animated style with the <strong>useAnimatedStyle</strong> Hook</li><li>Pass the animated style object to the Animated.View style prop</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e242fdaa2dd5e1833cd088644abf7d50/href">https://medium.com/media/e242fdaa2dd5e1833cd088644abf7d50/href</a></iframe><p>which leaves us with the following behaviour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*L4DOlbiCSpR2oZXKHHqHuQ.gif" /><figcaption>Implementation using RNGH v1 API with snapping</figcaption></figure><p><strong>useAnimatedGestureHandler</strong> expects an object with one or more callbacks defined. For our use case, we only need to take care of the <strong>onStart,</strong> <strong>onActive</strong> and <strong>onFinish</strong> callbacks. 1) As soon as the finger taps on the view and the gesture is recognised, we animate the <em>scale</em> and reflect the fact that the view is in the <em>pressed</em> state. 2) We need to drive the animation while the user is panning the view, so we map the translationX and translationY values extracted from the native event to our <em>shared values</em>. Finally, once the gesture finishes, we make sure to animate the <em>scale</em> back to its initial value and reflect the fact that the view is no longer in the <em>pressed</em> state.</p><p>In each callback, we have some information about the native event such as <strong>x, y, absoluteX, absoluteY, translationX, translationY, velocityX, velocityY.</strong></p><ul><li><strong>onStart:</strong> We set isPressed to <strong>true</strong> and the <em>scale</em> to the desired value (<strong>1.2</strong> in this case).</li><li><strong>onActive:</strong> We extract translationX and translationY , the values we are interested in, and set them to the posX and posY <em>shared values</em>, respectively.</li><li><strong>onFinish:</strong> We don’t need to extract any information from the native event in this case, so we simply animate the view back to its initial position using <strong>withTiming, </strong>then set isPressed back to false and the <em>scale</em> back to its initial value (<strong>0</strong>).</li></ul><blockquote>⚠️ It’s important to highlight that there is also an <strong>onEnd</strong> callback available. The difference with <strong>onFinish</strong> is that <strong>onEnd</strong> is only called if the gesture actually started and finished gracefully, meaning it went through the ACTIVE state. However, if you only tap your finger on the view and immediately release it without panning it, the pan gesture fails to be recognised, which triggers <strong>onFail</strong> and <strong>onFinish</strong>. So, the main takeaway here is knowing that <strong>onFinish</strong> will <strong>always</strong> be triggered regardless of whether the gesture was recognised or failed.</blockquote><p>If we simply replace the 2 calls to <strong>withTiming</strong> with <strong>withSpring</strong>, we get this nice behaviour instead 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*_IhddnMZFByynbvrAlPWSA.gif" /><figcaption>Using withSpring to animate the view</figcaption></figure><h4>Implementation With RNGH v1 API (Without Snapping)</h4><p>Getting it working without the snapping behaviour, that is, making the view <em>remember</em> and stay in the place where you lift the finger up is a bit trickier and requires a little more work, as <a href="https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/events#using-context">explained here.</a></p><blockquote>This simple modification makes things a bit more trickier and the reason is that when the new gesture is started, the translation values it provides in the event payload are relative to the starting position of the gesture. As a result, we cannot just directly map the gesture translation to the view offset on the screen. One way to solve this is by making a temporary state where we can keep the starting offset of the view. For this purpose we can use the context argument that is provided to each of the gesture handler worklets.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f7f67d41d1a87597416a311f41632fb/href">https://medium.com/media/0f7f67d41d1a87597416a311f41632fb/href</a></iframe><p>We have made a couple of modifications to our implementation:</p><ul><li><strong>onStart:</strong> We now save the starting position by setting the offset values to the current position (posX and posY, respectively) as soon as the gesture is recognised and started.</li><li><strong>onActive: </strong>We need to account for the offset when mapping the translationX and translationY values to the <em>shared values. </em>That’s why we add the value to the offset: posX.value = translationX + offsetX</li></ul><p>Finally, note how we are calling <strong>useAnimatedGestureHandler</strong> in this case by passing 2 <em>type parameters.</em> The first one represents the handler type (pan, tap, pinch, rotation, etc), and the second one represents the context object type. We do this so we can automagically get the proper typing for our context object when working with it inside the callbacks.</p><h4>Implementation Using RNGH v2 API (With Snapping)</h4><p>Migrating our implementation to use the new RNGH v2 API is actually quite straightforward. There are basically 2 steps involved:</p><ul><li>Define the gesture with RNGH Gesture API instead of Reanimated <strong>useAnimatedGestureHandler</strong> Hook.</li><li>Replace the PanGestureHandler with GestureDetector passing the gesture as prop to gesture</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c4c861073b88640d749d6feab8d079c/href">https://medium.com/media/3c4c861073b88640d749d6feab8d079c/href</a></iframe><p>And that’s it! Defining the gesture with the Gesture API looks almost the same. Know that there’s also Gesture.Tap(), Gesture.LongPress(), Gesture.Pinch(), and so forth and so on.</p><blockquote>⚠️ On a similar line regarding the subtle differences between the <strong>onEnd</strong> and <strong>onFinish</strong> callbacks when using the <strong>useAnimatedGestureHandler</strong> Hook, when using the Gesture API there is an <strong>onStart / onBegin</strong> and an <strong>onEnd / onFinalize. </strong>We need to use <strong>onBegin</strong> instead of <strong>onStart</strong> because <strong>onBegin</strong> is triggered as soon as you tap the view whereas <strong>onStart</strong> is triggered when the pan gesture actually starts. And we need to use <strong>onFinalize</strong> instead of <strong>onEnd</strong> for the same reasons explained in a previous paragraph.</blockquote><h4>Implementation Using RNGH v2 API (Without Snapping)</h4><p>Making the view stay in the place where we lift the finger up is just a bit different when working with the RNGH v2 API. Since we’re no longer using the <strong>useAnimatedGestureHandler</strong> Hook to define the gesture, we don’t have access to the <em>context</em> object that we were using to save the starting position.</p><p>The solution simply consists in defining 2 new <em>shared values</em> holding the offsetX and offsetY values, respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b31a2f2d24187da88a147c15d4d3e26f/href">https://medium.com/media/b31a2f2d24187da88a147c15d4d3e26f/href</a></iframe><h4>Wrapping Up</h4><p>I sincerely hope you enjoyed this article and that you were able to grasp the basics of working with simple pan gestures with the latest versions of these 2 amazing libraries! Stay tuned for more animation / gesture-related content in the context of React Native. Until next time! ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47da8d629280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power Of Template Literal Types In TypeScript]]></title>
            <link>https://medium.com/@taitasciore/the-power-of-template-literal-types-in-typescript-3708dc6ba202?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3708dc6ba202</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 12:16:41 GMT</pubDate>
            <atom:updated>2023-02-09T12:16:41.773Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring<strong> Template Literal Types</strong> in TypeScript with some real-world applications.</h4><p><strong>Template Literal Types</strong> could be thought of as a sort of JS template strings but at the type level. In JS, you can do this `My name is ${name}` . Similarly, in TypeScript you can do the following:</p><pre>type Hello = &#39;Hello&#39;;<br>type World = &#39;World&#39;;<br>type Greetings = `${Hello} ${World}`; // type is &#39;Hello World&#39;</pre><p>At first sight, this might not seem very useful, but when the <strong>Template Literal Type</strong> includes <em>unions of literal values</em>, things do get interesting. We could easily define a type that represents all the possible positions of a chess board.</p><pre>type ChessLetter = &#39;A&#39; | &#39;B&#39; | &#39;C&#39; | &#39;D&#39; | &#39;E&#39; | &#39;F&#39; | &#39;G&#39; | &#39;H&#39;;<br>type ChessNumber = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;<br>type ChessPosition = `${ChessLetter}${ChessNumber}`;</pre><p>ChessPosition represents the following type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYjidC7_FHnnNPCvVLQa1g.png" /></figure><p>So, you can see that when the <strong>Template Literal Type</strong> includes <em>unions of literal values,</em> the resulting type will be a <strong>union of all the possible combinations of values.</strong></p><h4>Taking it a step further</h4><p>We can combine <strong>Template Literal Types</strong> with <strong>Mapped Types, Key Remapping via </strong><strong>as,</strong> and some of the built-in utility types that operate on string types to generate really interesting types.</p><p>Consider the following interface:<em> </em>interface User { name: string; lastName: string; age: number } . We could then define a Getter that would generate the following type if we pass User .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*v31e3vzYjfp6dmezfT01yQ.png" /></figure><p>This is how you would define such a type. We’ll go over each step of the way:</p><p>type Getter&lt;T&gt; = { [P in keyof T &amp; string as `get${Capitalize&lt;P&gt;}`]: () =&gt; T[P] }</p><p>Getter takes a <em>type parameter</em> T . Then, we have a <strong>Mapped Type</strong> iterating over the keys of T . As we are iterating, we are also <em>remapping</em> the keys via as . This allows us to <em>remap</em> the keys to whatever string we desire. Combining <strong>Template Literal Types</strong> with the built-in Capitalize utility type, we are able to model this syntax at the type level: <em>property -&gt; getProperty. </em>Finally, we map the types to <strong>functions that return the original type.</strong></p><p>We can also easily define a Setter type that would generate the set of setters for a given <em>object:</em></p><p>type Setter&lt;T&gt; = { [P in keyof T &amp; string as `set${Capitalize&lt;P&gt;}`]: (arg: T[P]) =&gt; void }</p><p>which generates the following type when User is passed as <em>type parameter:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*lNfkdEYI3ciNFjQmExO_rA.png" /></figure><p>As you can see, it only involved some slight modifications to the previous type.</p><h4>Enforcing Certain Format For Screen Names</h4><p>We can use Template Literal Types to enforce certain format on the strings we set, for instance, for screen names:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a0ab9f2ec1bdb5680a0aa43c09e411/href">https://medium.com/media/06a0ab9f2ec1bdb5680a0aa43c09e411/href</a></iframe><p>If there’s a lower-cased letter on the string literal or if the string literal does not end with _SCREEN , the TypeScript compiler will complain!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3708dc6ba202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Pan And Scroll Gestures Simultaneously And Gracefully With Gesture Handler 2, Reanimated…]]></title>
            <link>https://medium.com/@taitasciore/handling-pan-and-scroll-gestures-simultaneously-and-gracefully-with-gesture-handler-2-reanimated-63f0d8f72d3c?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f0d8f72d3c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reanimated]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[gesture-handler]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 11:07:55 GMT</pubDate>
            <atom:updated>2023-01-27T11:11:06.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling Pan And Scroll Gestures Simultaneously And Gracefully With Gesture Handler 2, Reanimated 2, And TypeScript</h3><h4>Handling and reconciling both gestures, pan and scroll, when working with a ScrollView smoothly.</h4><p>Recently, I was working on a simple todo-list app as a side project to explore the different solutions available for state management in the React (Native) ecosystem such as <a href="https://reactjs.org/docs/context.html">Context</a>, <a href="https://redux.js.org/introduction/getting-started#redux-toolkit">Redux with RTK</a>, <a href="https://github.com/pmndrs/zustand">Zustand</a>, <a href="https://recoiljs.org/">Recoil</a>, <a href="https://jotai.org/">Jotai</a>, <a href="https://mobx.js.org/">MobX</a>.<em> </em>I was inspired by the minimalistic UI and UX in an app called <a href="https://apps.apple.com/us/app/minimalist-to-do-list-task/id993066159">MinimaList, available on iOS.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pj7dOQPH6AImUQTMnpgzvw.jpeg" /></figure><p>The list of tasks is displayed with a very simple design. Scrolling up from the top of the list will trigger an action, redirecting you to another page where you can add a new task. I found this quite nice and felt inspired to replicate this behaviour in my app, even though the project was more about playing around with state management rather than a fancy UI / UX. I admit that, eventually, I became a little obsessed with it and started thinking of ways to achieve something similar. It took a lot of frustration, trial and error, searching online trying to find hints somewhere, in StackOverflow or somewhere else. I did not find many examples related to what I was trying to implement neither on the Reanimated nor on the Gesture Handler official docs. I found a couple of hints hidden in some examples in the RNGH repository, but they were using the old v1 API. I was <strong>determined</strong> to get it working with the <strong>latest</strong> versions and APIs of both libraries.</p><h4>React Native Gesture Handler</h4><p>The old RNGH API was all about <em>gesture handlers</em>. You would have <strong>TapGestureHandler</strong>, <strong>PanGestureHandler</strong>, <strong>PinchGestureHandler,</strong> <strong>RotationGestureHandler</strong>, among others, at your disposal. Composing them together to be able to handle multiple gestures and define the relationship between them required stacking them on top of each other, resulting in <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/guides/upgrading-to-2#using-multiple-gestures-on-the-same-view">something like this.</a></p><p>In the new API, as the official docs say:</p><blockquote><em>GestureDetector is the main component of the RNGH2. It is responsible for creating and updating native gesture handlers based on the config of provided gesture. The most significant difference between it and old gesture handlers is that the </em><em>GestureDetector can recognize more than one gesture at the time thanks to gesture composition. Keep in mind that </em><em>GestureDetector is not compatible with the </em><a href="https://reactnative.dev/docs/animated"><em>Animated API</em></a><em>, nor with </em><a href="https://docs.swmansion.com/react-native-reanimated/docs/1.x.x/"><em>Reanimated 1</em></a><em>.</em></blockquote><p>GestureDetector takes a single prop gesture , a gesture or a composition of gestures. The <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/api/gestures/gesture">gestures</a> themselves are quite easy to define with the builder pattern! You can find more information about the available gesture <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/api/gestures/gesture">here</a>. You can have something like Gesture.Tap() or Gesture.Pan(), etc and then start chaining the different callbacks and properties to define the desired gesture. Each gesture has its own set of properties. There are, however, some common properties shared between all gestures.Y</p><p>There are also <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/api/gestures/composed-gestures">Composed Gestures</a> like Gesture.Simultaneous(), Gesture.Exclusive(), Gesture.Race() , and others, which accept 2 or more gestures as arguments, to provide a simple way of building relations between gestures.</p><h4>React Native Reanimated</h4><p>As for Reanimated 2, I felt a lot more comfortable with its API since I’ve invested some time exploring it in the past and have had the chance to do a couple of cool things with it. Nonetheless, I <em>did</em> learn some new things on the way.</p><p>The really tricky part, at least for me, was having to support both pan and scroll gestures simultaneously. If the scroll position is 0, the top of the list, we need to handle and support pan gestures, downwards only like a swipe down; and we move the list accordingly with a translation on the Y axis, simulating a scroll, because it’s not possible to scroll on a short list, meaning the onScroll callback won’t be triggered. But if the scroll position is anywhere else other than at the top, pan gestures must be disabled since scrolling down on the list would also trigger the pan gestures, causing a weird and undesirable behaviour.</p><h4>Creating Our Component</h4><p>I won’t go over on how to setup RNGH and Reanimated. Make sure to install the dependencies with npm i react-native-gesture-handler react-native-reanimated and follow both installation guides:</p><ul><li><em>React Native Gesture Handler: </em><a href="https://docs.swmansion.com/react-native-gesture-handler/docs/installation"><em>https://docs.swmansion.com/react-native-gesture-handler/docs/installation</em></a></li><li><em>Reanimated: </em><a href="https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation"><em>https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation</em></a></li></ul><p>We can finally start to implement our component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e90f058412a18c1ed4f663aeab2bd030/href">https://medium.com/media/e90f058412a18c1ed4f663aeab2bd030/href</a></iframe><p>A few things to note here. The TextInput has its position set to ‘absolute’, and its position will be driven by the pan gesture defined for the ScrollView</p><h4>Using The Animated Versions Of The Components</h4><p>The next thing we can do is use the <em>animated</em> versions of the components, since we will be passing animated style objects created with useAnimatedStyle() to the styles prop. Reanimated ships with an Animated.ScrollView component, so we can just import and use that one instead. For the TextInput, we can create the animated version of it by passing it to Animated.createAnimatedComponent() and that leaves us with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba4ed75fda3ae3092711a0b9a08b61e1/href">https://medium.com/media/ba4ed75fda3ae3092711a0b9a08b61e1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*gd6gliHc5q53VqDcYuwL-Q.png" /></figure><p>You might have noticed that the TextInput is not visible in the screen. It is actually being rendered but, since it’s <em>absolutely</em> positioned and it’s rendered before the ScrollView, it ends up being displayed under the ScrollView because it’s not part of the view hierarchy.</p><blockquote><em>If you add </em><em>{ zIndex: 1 } to its style, it will be visible.</em></blockquote><h4>Creating The Shared Values And Animated Styles</h4><p>We will apply a transformation on translationY<em> </em>to position the TextInput above the ScrollView and out of the screen bounds, in its initial position.</p><p>First, we create a <em>shared value</em> for the TextInput with useSharedValue() and then an animated style object with useAnimatedStyle()</p><pre>import { useAnimatedStyle, useSharedValue } from &#39;react-native-reanimated&#39;;<br><br>const INITIAL_POS_Y_INPUT = -50;<br><br>// Inside the component<br>const inputSv = useSharedValue(INITIAL_POS_Y_INPUT);<br><br>const inputAnimatedStyle = useAnimatedStyle(() =&gt; ({<br>  transform: [{ translateY: inputSv.value }],<br>}));</pre><p>Remember to pass this style object as style prop to the TextInput . Then, we do the same with the ScrollView</p><pre>import { useAnimatedStyle, useSharedValue } from &#39;react-native-reanimated&#39;;<br><br>const INITIAL_POS_Y_INPUT = -50;<br><br>// Inside the component <br>const scrollSv = useSharedValue(0);<br><br>const scrollAnimatedStyle = useAnimatedStyle(() =&gt; ({<br>  transform: [{ translateY: scrollSv.value }],<br>}));</pre><p>Oh, yes… you will also need to install react-native-redash , a library that ships with some helpers and utilities to work with Reanimated and RNGH in an easier way.</p><p>Remember to pass this style object as style prop to the ScrollView as well!</p><h4>Handling The Pan Gesture</h4><p>Let’s first try to get this working with only the pan gesture without worrying about scrolling just yet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4be75e112d69ce47f8a2e0112c384e/href">https://medium.com/media/ed4be75e112d69ce47f8a2e0112c384e/href</a></iframe><p>While the gesture is in the ACTIVE state and the view is being moved (panned), onUpdate callback will receive all the updates regarding the current position with some <a href="https://docs.swmansion.com/react-native-gesture-handler/docs/api/gestures/pan-gesture#event-data">information about the native event specific to <strong>PanGesture</strong></a> such as translation, velocity, among others. We are <em>clamping</em> the value for translationY because we want control over which values are feed to the transformation when defining the animated style object. So, we want to have a <em>lower</em> and <em>upper</em>bound. We don’t want negative values for the <em>Y axis</em>, that is, the ScrollView moving upwards. We only want it to move between 0 and -INITIAL_POS_Y_INPUT, that is, the amount of space it takes for the TextInput to come down and pop up from above. We then need to <em>interpolate</em> this value because panning on the ScrollView upwards generates negative values and we want to move the TextInput downwards, which require positive values.</p><p>onFinalize callback is triggered whenever a gesture ends, whether because it failed or because it was recognised and finished.</p><p>Here, if we move the ScrollView upwards by at least -INITIAL_POS_Y_INPUT , we navigate to the desired page and we trigger a delayed timing animation so that both the TextInput and ScrollView go back to their initial position. We want to delay the execution of the animation until after we have navigated to the next screen, because it looks a little weird navigating to another screen while also seeing these 2 views move. We need to wrap our navigation function call with runOnJS() since the gesture callbacks are <em>worklets,</em> special functions marked to be run on the UI thread. This is one of the core principles of Reanimated 2. So, we need to switch back to the JS thread explicitly while working in this scope to be able to call our functions.</p><p>Finally, if we didn’t move the view enough to go over the threshold (INITIAL_POS_Y_INPUT) , we also trigger a timing animation to make both views go back to their initial position, except this time we don’t need to delay their execution.</p><h4>The Native Gesture</h4><p>Native gestures are one of the new concepts I took with me from this project and it was crucial in achieving the desired behaviour.</p><blockquote><em>A gesture that allows other touch handling components to participate in RNGH’s gesture system. When used, the other component should be the direct child of a </em><em>GestureDetector.</em></blockquote><p>What we want to do is define a native gesture for our ScrollView component: const nativeGesture = Gesture.Native()</p><p>As mentioned before, handling multiple gestures with the legacy RNGH API required stacking several gesture handler components on top of each other. And to define the relationship between them required setting a <em>ref</em> on each of them as well as passing either a simultaneousHandlers or waitFor prop with a <em>ref</em> or array of <em>refs</em>, so 2 or more gesture handlers would be pointing to each others’ <em>refs</em> through those props.</p><p><em>Gesture Composition: </em><a href="https://docs.swmansion.com/react-native-gesture-handler/docs/gesture-composition"><em>https://docs.swmansion.com/react-native-gesture-handler/docs/gesture-composition</em></a></p><blockquote><em>Composing gestures is much simpler in RNGH2, you don’t need to create a ref for every gesture that depends on another one.</em></blockquote><p>Since we’re working with a ScrollView, we should make it aware of the gesture system and, because it’s the direct child of the GestureDetector, defining a native gesture will do the trick here. Finally, we want to support pan and scroll gestures simultaneously, so that’s why we compose both with Gesture.Simultaneous()</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstreamable.com%2Fo%2Fshhw1w&amp;display_name=Streamable&amp;url=https%3A%2F%2Fstreamable.com%2Fshhw1w&amp;image=https%3A%2F%2Fcdn-cf-east.streamable.com%2Fimage%2Fshhw1w.jpg%3FExpires%3D1675076640%26Signature%3DG3gJOGNiq7m%7EpXIzE48NXX0moHPj4j7bFAW-r-eVwxXf8%7E%7EdGMzydw2rJE6-fhU7LXXF5m1I6-xIV-o%7EwGrSjucGJLmlkI-GqD9NKJpgXWu40sD%7E1frzqptGINhvAr8LbdpDCNbjWBhDNV%7EyWmgtO2Z8ALONZe6Wp4-ZvyvxENzGErqjoB3mdrlYaWwdY4dEzOEWKMoW2sLpXFVMj1sZdu9t5sEckY0rZw8CK83uhsXWsPic1eA87p0fGF4R8J6B4LOG8vlNfjrn5sMqx-vUNthyhdiERZW4W5DlhtqeTu07DINYzyfg-%7ErmKRGGJvtbzEAcENmZ192ijo6M5V-G2g__%26Key-Pair-Id%3DAPKAIEYUVEN4EVB2OKEQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=streamable" width="330" height="718" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2c3279a8a741e7a6bf8588bb9a4535/href">https://medium.com/media/9c2c3279a8a741e7a6bf8588bb9a4535/href</a></iframe><h4>Disabling The Pan Gesture Dynamically</h4><p>We’re almost there! We need to handle the last use case: scrolling down, stopping, and scrolling up will trigger the pan gesture, which is not desirable in this case. We want the pan gesture to be recognised only if we’re at the top of the list (scroll position = 0).</p><p>One of the chainable methods available to all gestures is .isEnabled(boolean) so, it’s clear we need to have some flag handed by the local state.</p><pre>const [isPanEnabled, setIsPanEnabled] = useState(true);</pre><p>Then, we will use useAnimatedScrollHandler to define the scroll handler for the ScrollView. We will pass this as the onScroll callback. If at the point of releasing dragging or momentum end, we are not at the top of the list, we disable the pan gesture. Otherwise, we enable it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/663fdda4e0f2b58a7bd7899842234f10/href">https://medium.com/media/663fdda4e0f2b58a7bd7899842234f10/href</a></iframe><p>And the final implementation of our component is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9f829169bfd70b031860d146c38316a/href">https://medium.com/media/b9f829169bfd70b031860d146c38316a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstreamable.com%2Fo%2Fj6kh0c&amp;display_name=Streamable&amp;url=https%3A%2F%2Fstreamable.com%2Fj6kh0c&amp;image=https%3A%2F%2Fcdn-cf-east.streamable.com%2Fimage%2Fj6kh0c.jpg%3FExpires%3D1675076760%26Signature%3DJ2zzFjDOSemvi9qycPYlxmoq1DqTXaGrvj9KsSEU-FpfO6jcNvZs1WKxqEARe33%7ETYgzzUqPVEe4ZsDa-wsSY0QaEeZ6c686yv2PzMRyJK1BtCq1vVJgi4fTK8Obo87AYb5XaFj85so3bj36Pr-kanfjq8LRUSItlr%7E4tFfcdT3ORkSs9-Kx8Col2vxj2OMeJnjidbUwkM%7ExA6ihdR-pxfDGyDp1beW5IaqgRiUvKxWEo7QdavCZg2NT6JpMuPaxvvcBqmSRo3I0t1767xjjRhJTQyinaJrQc-6McRVRKJkY1j0QMfW7oBWHzVjPT59lchR0oqu54AbRtQcAHG8yUg__%26Key-Pair-Id%3DAPKAIEYUVEN4EVB2OKEQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=streamable" width="330" height="718" frameborder="0" scrolling="no"><a href="https://medium.com/media/00911d55bd65e2073cd4394d3a0f165d/href">https://medium.com/media/00911d55bd65e2073cd4394d3a0f165d/href</a></iframe><h3>Yay! 😍</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f0d8f72d3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Wrapping Your Redux Action Creator Calls With dispatch()]]></title>
            <link>https://medium.com/@taitasciore/stop-wrapping-your-redux-action-creator-calls-with-dispatch-458396300331?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/458396300331</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 17:43:41 GMT</pubDate>
            <atom:updated>2023-01-25T12:43:57.465Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating a custom Hook to wrap your Redux action creator calls with dispatch() with TypeScript so that you can call them like regular functions.</h4><p>I don’t know about you, but I’ve come across bugs (more than once) in the past related to some <em>action </em>not being dispatched, the reason being only that the <em>action creator</em> was not wrapped with <strong>dispatch()</strong>, but called as a regular function instead:</p><pre>addProductToCart(product); // WRONG<br>dispatch(addProductToCart(product)); // OK</pre><p>We will create a custom Hook to do the work of wrapping the function call with <strong>dispatch()</strong>, so that we can dispatch our <em>actions </em>calling them like regular functions! Let’s jump right in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBfaLdmhxoye1u1WavKlQQ.png" /><figcaption>Implementation of custom Hook useWithDispatch</figcaption></figure><p>The implementation is pretty straightforward. useWithDispatch is a <em>higher-function</em> since it receives a function (the <em>action creator</em>) as argument and returns another function which, when called, will call the passed function wrapped with <strong>dispatch()</strong>. The challenge lies in getting the types right with the <em>generic type parameters.</em></p><p>We first declare a <em>type parameter</em> Type of type string. This represents the <em>action type</em>, a <strong>string literal type</strong>. We then declare another type parameter Payload, representing the <em>payload type</em>, which could be anything. We pass both to ActionCreatorWithPayload , a type imported from RTK. This allows us to have strict type safety when calling the method. Finally, we make sure to <em>memoize</em> the callback with useCallback.</p><p>Let’s say we’re working on a todo-list app and have a type Task and an action addTask() which takes a Task and adds it to the list of tasks:</p><pre>// actions.ts<br>import { createAction } from &#39;@reduxjs/toolkit&#39;;<br><br>const addTaskAction = createAction&lt;Task&gt;(&#39;tasks/addTask&#39;);<br><br>// Our component<br>import { addTaskAction } from &#39;./actions&#39;;<br>const addTask = useWithDispatch(addTaskAction);<br>addTask(task);</pre><p>If we hovered the mouse over the <em>enhanced</em> addTask(), we would see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*SHZGFYMsp9FF6npB5vqmsw.png" /><figcaption>Type safety when dispatching our actions</figcaption></figure><p>We still get the same type safety when calling the function as if we were doing it the regular way: dispatch(addTask(task))</p><h4>Wrapping Up</h4><p>I hope you found this blog post useful. You still need to remember to pass your <em>action creators</em> to useWithDispatch, but it will be easier to remember doing it right after importing the <em>actions</em> into your components than when calling them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458396300331" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Removing Falsy Values From An Array With TypeScript In A Truly Type-Safe Way]]></title>
            <link>https://medium.com/@taitasciore/removing-falsy-values-from-an-array-with-real-type-checking-with-typescript-31d283174431?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d283174431</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 11:26:37 GMT</pubDate>
            <atom:updated>2023-01-21T11:35:37.609Z</atom:updated>
            <content:encoded><![CDATA[<h4>Filtering out falsy values whilst getting the real resulting type with TypeScript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBTd0nx_SviVj6o1ZK03XA.jpeg" /><figcaption>Image taken from <a href="https://geekstutorials.com/wp-content/uploads/2021/05/JavaScript-Array-Filter.jpg">https://geekstutorials.com</a></figcaption></figure><p>As you know, there are 6 <em>falsy</em> values in JavaScript: null | undefined | false | 0 | ‘’ | NaN. You probably also know how to remove <em>falsy</em> values from an array in JavaScript using the Array.filter() function:</p><pre>arr.filter(elem =&gt; !!elem);</pre><p>We can even make it shorter:</p><pre>arr.filter(Boolean);</pre><h4>The Problem: Developer Experience</h4><p>This works in runtime as expected. However, when working with TypeScript, we don’t get the expected type after filtering out the <em>falsy</em> values. We <em>know</em> that the array does not contain <em>falsy</em> values, but for TypeScript, the resulting array could, <em>in theory</em>, contain them. Basically, TypeScript is not able to narrow down the type of the resulting array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUQRhd4yTEZMHEKVwwos4A.png" /></figure><p>filteredNumbers does in fact <strong>not</strong> contain <em>falsy</em> values, but the resulting type is still the same. This is not a huge issue, but it’s not the ideal DX because we have to use <em>optional chaining</em> all over the place, or even worse, the <em>non-nullish</em> operator.</p><h4>The Solution</h4><p>Improving this turns out to be quite easy. We can use some of TypeScript utility types to accomplish what we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1Tx3QJ-0JTXPYauHvwJ4g.png" /><figcaption>Removing falsy values in a truly type-safe way</figcaption></figure><p>If we call <strong>sift()</strong> passing the numbers array defined above, TypeScript will tell us that the type is just number !</p><blockquote>Note that if you don’t want to define this function yourself, you can just install radash and use the <strong>sift()</strong> array method. Radash is sort of a more compact and modern, type-safe lodash.</blockquote><h4>Resources</h4><p><em>Radash: </em><a href="https://radash-docs.vercel.app/docs/getting-started"><em>https://radash-docs.vercel.app/docs/getting-started</em></a></p><p><strong><em>sift()</em></strong><em> method: </em><a href="https://radash-docs.vercel.app/docs/array/sift"><em>https://radash-docs.vercel.app/docs/array/sift</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d283174431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 Spread Operator In Depth When Using TypeScript]]></title>
            <link>https://medium.com/@taitasciore/es6-spread-operator-in-depth-when-using-typescript-192862804498?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/192862804498</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 11:49:28 GMT</pubDate>
            <atom:updated>2023-01-20T11:49:28.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using the Spread operator at its full potential</h4><p>We’ll first go over the basics of the spread operator before introducing some not-so-known uses for it.</p><blockquote>The Spread operator makes it possible for arrays and objects to be expanded.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGJoxPLGAmecqqEkj62_jQ.jpeg" /><figcaption>Image taken from <a href="https://i.ytimg.com/">https://i.ytimg.com/</a></figcaption></figure><p>First of all, you may have noticed that the <em>Spread</em> and <em>Rest</em> operators look exactly the same. They both use the same syntax with the <em>three dots</em> (<strong>…</strong>) but, actually, one can be seen as the opposite of the other. That is, they accomplish opposite things. We’ll take a look at using the spread operator on arrays and objects separately.</p><h3>Spreading Arrays</h3><p>As stated above, the spread operator will expand an array into its elements where one or more values are expected. The consequence of this is that the array will be <em>flattened</em>. Let’s look at an example.</p><p>Say you want to concatenate or merge two arrays, so you go ahead and, with the best of your intentions, come up with this:</p><pre>const arr = [4, 5, 6];<br>const resultArr = [1, 2, 3, arr];</pre><p>If you <em>console.log</em> resultArr, you will see that the output is: [1, 2, 3, [4, 5, 6]]. Oops! Not quite what we wanted. Here’s where the spread operator comes in. If we type const resultArr = [1, 2, 3, …arr] instead, you will see that the following is printed: [1, 2, 3, 4, 5, 6]. Nice. Hopefully, with this example is now clear what is meant when I say the array is <em>expanded</em>.</p><p>So, concatenating arrays is one of the most common uses of the spread operator:</p><pre>const arr1 = [1, 2, 3];<br>const arr2 = [4, 5, 6];<br>const resultArr = [...arr1, ...arr2];</pre><p>Keep in mind that <strong>spreading an array or object will create a new copy of it,</strong> with a new reference in memory, so this is great news for <strong>immutability.</strong></p><p>Before the spread operator, you needed to rely on some of the array methods that are immutable in order to copy or concatenate arrays. When I say <em>immutable</em>, I’m talking about methods that don’t mutate the incoming array, that is, they work on and with a new and fresh copy of the incoming array and return that one instead.</p><pre>const arr1 = [1, 2, 3];<br>const arr2 = [4, 5, 6];<br>const resultArr = arr1.concat(arr2); // Concatenates two arrays<br>const copyArr = arr1.concat([]); // Creates a new copy of arr<br>const copyArr = arr1.slice(0); // Also creates a new copy of arr</pre><h3>Spreading Objects</h3><p>The spread operator works similarly with objects as it does with arrays. It also allows us to copy objects.</p><h4>Copying Objects</h4><pre>const user1: User = {<br>  id: &#39;some_id&#39;,<br>  firstName: &#39;Foo&#39;,<br>  lastName: &#39;Bar&#39;,<br>  email: &#39;foobar@hotmail.com&#39;,<br>};<br><br>const user2: User = { ...user1 };</pre><p>As you can see, the syntax is quite similar as when spreading arrays.</p><h4>Applying Partial Updates Or Modifications</h4><p>Not only can you use the spread operator to copy an object, but you can also use it to both copy and apply <em>partial</em> updates or modifications to its properties, at the same time.</p><pre>const user1: User = {<br>  id: &#39;some_id&#39;,<br>  firstName: &#39;Foo&#39;,<br>  lastName: &#39;Bar&#39;,<br>  email: &#39;foobar@hotmail.com&#39;,<br>};<br><br>const user2: User = {<br>  ...user1,<br>  firstName: &#39;Another Name&#39;,<br>  lastName: &#39;Another Last Name&#39;,<br>};<br><br>const user3: User = { ...user2 };</pre><h4>Copying And Updating Deep And Nested Objects</h4><p>Keep in mind that it does not matter how deep or nested the shape of the object you are working with might be. You can continue to apply the spread operator at each level, copying each level as necessary:</p><pre>const nestedObject: NestedObject = {<br>  a: {<br>    b: {<br>      c: {<br>        d: {<br>          e: {<br>            someProp: &#39;test&#39;,<br>            anotherProp: true,<br>            yetAnotherNestedProp: { itEndsHere: 7 },<br>          },<br>        },<br>      },<br>    },<br>  },<br>};<br><br>const anotherNestedObject: NestedObject = {<br>  ...nestedObject,<br>  a: {<br>    ...nestedObject.a,<br>    b: {<br>      ...nestedObject.a.b,<br>      c: {<br>        ...nestedObject.a.b.c,<br>        d: {<br>          ...nestedObject.a.b.c.d,<br>          e: {<br>            ...nestedObject.a.b.c.d.e,<br>            someProp: &#39;change&#39;,<br>            anotherProp: false,<br>          },<br>        },<br>      },<br>    },<br>  },<br>};</pre><p>This might be a little exagerated, but you get the point. Here, we have copied nestedObject all the way down to e . Then, we have updated the values of someProp and anotherProp . Since we have copied e with ...nestedObject.a.b.c.d.e, the prop yetAnotherNestedProp will keep the same value as it does in the original nestedObject . In a nutshell, using the spread operator will copy an object and all its properties, so we just need to update or change the ones we’re interested in at each level of the object.</p><h4>Merging Objects</h4><p>Note that when using the spread operator to merge 2 or more objects, if they happen to have common properties, the one from the last spread object will be used as source of truth:</p><pre>const user1 = {<br>  id: &#39;some_id&#39;,<br>  firstName: &#39;Foo&#39;,<br>  lastName: &#39;Bar&#39;,<br>  email: &#39;foobar@hotmail.com&#39;,<br>};<br><br>const user2 = {<br>  ...user1,<br>  firstName: &#39;Another Name&#39;,<br>};<br><br>const finalUser = { ...user1, ...user2 };</pre><p>If you<em> console.log</em> finalUser, you will see that firstName holds the value <em>‘Another Name’.</em></p><h3>Common And Not-So-Common Uses For The Spread Operator</h3><p>We’ll revisit the most common and known uses for the spread operator and also take a look at some other interesting tricks we can do with it:</p><ul><li><strong>Copying an object:</strong> If you work with React, you may have been using this for a while without knowing, because this is related to <strong>immutability,</strong> one of the core principles behind Redux. In a nutshell, we can use the spread operator to make sure we’re not <em>mutating</em> an object, but rather always working with a new and fresh copy of it. Why is this important? An image speaks more than 1000 words:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*OPsYz05W0OmUlOGFpLz_Gw.png" /><figcaption>No spread operator used. Object is mutated</figcaption></figure><p>Here, we’re not using the spread operator, so we are actually <em>mutating</em> the user object. What does this mean? That userCopy <strong>is</strong> <em>literally</em> the same as user . It points to the same reference, the same space in memory, so changing a property of userCopy , as I have done in the previous snippet, will also be reflected in user . After that line, both user.firstName and userCopy.firstName will hold the value <em>‘whatever’.</em> This is undesirable and can quickly lead to bugs and issues than can be very hard to debug and trace. As stated above, you can also use the spread operator to copy arrays.</p><ul><li><strong>Apply partial updates or modifications:</strong> Using the spread operator, we can safely copy the user object and update whatever props we want and rest assured the original user object won’t be affected in any way by these changes:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vnm7LKgAoq5faHzm4-TbaA.png" /><figcaption>Using the spread operator to copy an object and apply partial updates or modifications</figcaption></figure><p>Keep in mind that if want to update nested properties, we need to make sure to copy at each level as well and updates the properties we’re interested in at each level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJKFenZaqmGtx6VzcVYaRA.png" /><figcaption>Using the spread operator to update nested properties</figcaption></figure><ul><li><strong>Merge objects:</strong> We can use the spread operator to merge 2+ objects:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*nFemiv2fGqq6uIqNR5Qmsg.png" /><figcaption>Using the spread operator to merge 2 objects</figcaption></figure><ul><li><strong>Concatenate arrays:</strong> We can use the spread operator to merge 2+ arrays:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*BZQAnHh9-0Dl1bPBDGhAWw.png" /><figcaption>Using the spread operator to concatenate 2 arrays</figcaption></figure><ul><li><strong>Create an array of unique values, also called a <em>set:</em></strong><em> </em>[…new Set(arr)]<strong> </strong>. I have to say I really love this one!<strong> 😍</strong></li><li><strong>Expand an array or tuple in function calls:</strong> If we have an array or tuple, we can use the spread operator to expand its elements in a function call, so that each element is mapped to a function parameter:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*7N1zWkmoiwB6srrgF1tXYw.png" /><figcaption>Using the spread operator in function calls</figcaption></figure><p>This works because, if you take a look at the signature of either Math.min or Math.max , you will see they take <em>rest parameters</em> of type number[]. I do plan to write an article dedicated to <em>rest parameters</em> and, in consequence, the rest operator. At the beginning of this article, I brought up the fact that the spread and rest operators look exactly the same, however they perform rather opposite actions. We can use this example to understand this connection and relationship more clearly. The method expects ...number[] and we have an array. So, we know that the spread operator expands an array into its elements.</p><p>We can do something similar with <em>tuples</em> without working with <em>rest parameters:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTKSXxrvXSgg38cB2EqeGw.png" /><figcaption>Using the spread operator with tuples in function calls</figcaption></figure><p>⚠️ ️Note that the <strong>Const Assertion</strong> (with <strong>as const</strong>) is required and necessary for the above snippet to work. Why? I wrote an article on <strong>Const Assertions and Type Narrowing &amp; Widening </strong>where I explain this in depth.</p><p><em>Const Assertions And Type Narrowing &amp; Widening In TypeScript: </em><a href="https://medium.com/@taitasciore/const-assertions-and-type-narrowing-widening-in-typescript-72005b201f28"><em>https://medium.com/@taitasciore/const-assertions-and-type-narrowing-widening-in-typescript-72005b201f28</em></a></p><p>Without it, the TypeScript compiler will yell at us with <strong>A spread argument must either have a tuple type or be passed to a rest parameter. </strong>What does this mean?</p><p>Basically, someMethod expects a <strong>fixed</strong> number of arguments: <strong>3</strong> in this case, and of type number . We know that arr is an array of numbers. Arrays, <em>unlike</em> tuples, <strong>do not </strong>have a fixed length or size, so they are allowed to change. Since they can have an arbitrary number of elements and someMethod expects only 3 arguments, TypeScript won’t let us call the function like this. However, turning arr into a tuple with the <strong>Const Assertion,</strong> TypeScript realises it is safe for us to do this, because it knows arr is of type [number, number, number]. Well, more precisely, of type readonly [1, 2, 3] . In the end, this would be the same as calling the function like someMethod(1, 2, 3)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192862804498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 Destructuring In Depth When Using TypeScript]]></title>
            <link>https://medium.com/@taitasciore/es6-destructuring-in-depth-when-using-typescript-bdf7c899768a?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdf7c899768a</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 17:35:39 GMT</pubDate>
            <atom:updated>2023-01-17T17:35:39.874Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Destructuring at its full potential</h4><p>We’ll first go over the basics of destructuring before introducing some not-so-known uses for it.</p><blockquote>Destructuring makes it possible to <em>unpack</em> values from arrays or objects into different variables</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00N9Hs5KCX9IwNepd7Id4A.jpeg" /><figcaption>Image taken from <a href="https://xoor.io/">https://xoor.io/</a></figcaption></figure><h3>Destructuring Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*CyOusrkRxuYbXG0klN2xiw.png" /></figure><p>I’m sure you’ve written code like this yourself. Having to repeat oneself so much with res. every time you want to access one of its properties is cumbersome. To work around this, we have the destructuring assignment introduced in ES6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*cHp71O-8SQW9R8Q5ABXluA.png" /><figcaption>The same code using destructuring</figcaption></figure><p>That’s a lot more concise. And notice how we’re setting the value for id . When both variables have the same name, { id: id } can become just { id } . You will see why this could be useful.</p><h4>Renaming Destructured Properties</h4><p>It’s possible to rename the destructured properties. Knowing that if both variables have the same name, we can have a shorter syntax, we could easily do the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*wj60dY1g_3-3mqRMaLhKAA.png" /><figcaption>Using destructuring and renaming some properties</figcaption></figure><h4>Setting Default Values For Destructured Properties</h4><p>It’s also possible to set default values for the destructured properties that are optional:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*MVcm13tA_01gTXjOSFtBlA.png" /><figcaption>Using destructuring and setting default values</figcaption></figure><p>This might be useful, for instance, when mapping API responses so that we don’t have to deal with <em>nullish</em> values and have our codebase filled with <em>optional chaining</em> and stuff.</p><p>Notice the resulting type when we set a default value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*w9VaZ1qWsm8WycCCwF1gKQ.png" /></figure><p>Keep in mind that if we don’t set a default value, phoneNumber will have the type string | undefined</p><h4>Destructuring Nested Properties</h4><p>The great thing about destructuring is that it can be applied as many levels deep as necessary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*buZ5Remlz2sL45RSYSrB1g.png" /><figcaption>Destructuring nested properties</figcaption></figure><p>Now, let’s say b had other properties in it and we wanted to destructure them but also have access to the <em>whole</em> of b . We can do that!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*1LvRSvwMWuuH2L4tXK4-IQ.png" /></figure><p>Notice we type b, then destructure its properties. Both are possible at the same time!</p><h3>Destructuring Arrays And Tuples</h3><p>It’s also possible to destructure values from arrays (and tuples!). This is really useful because we can both destructure and assign meaningful names to the elements at the indices we want at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*SZJG9ut3NKOki9M7OkUIQw.png" /><figcaption>Using destructuring to unpack values from arrays and tuples</figcaption></figure><p>This is really nice because we don’t have to deal with range[0] or range[1] in our codebase, plus we also end up saving a couple of keystrokes because we don’t need to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*be1xCNDJB6BVXAvrTo9HAA.png" /><figcaption>The same code without destructuring</figcaption></figure><p>If you’re working with tuples, which, by definition, have a fixed length, you will get an error from the TypeScript compiler if you attempt to destructure more elements than are contained in the tuple, like const [min, max, other] = range<strong> Tuple type ‘Range’ of length ‘2’ has no element at index ‘2’.</strong></p><h4>Setting Default Values For Destructured Elements</h4><p>As with objects, it’s also possible to set default values for the destructured elements from arrays and tuples. For example, we might want to make sure that the first position of an array is always defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G33u7jQOE-7bUOXI1Vzohg.png" /><figcaption>Using destructuring to set default values for array elements</figcaption></figure><p>Now off to the fun part!</p><h3>Destructuring Tricks</h3><ul><li><strong>Excluding or omitting properties:</strong> We can use destructuring together with <em>rest parameters</em> with the <em>rest</em> operator to exclude or omit properties from an object. This is specially useful when working with React. Sometimes, you need to pass a lot of props to a component and might be tempted to just spread them all like &lt;Component {…props} /&gt; because it can be tedious to set them one by one. But, doing so, we might be passing some extra or unnecessary props that the component neither needs nor expects.</li></ul><p>I wrote 2 articles touching on this topic:</p><ul><li><em>Explicit Props Spreading In React Components: </em><a href="https://medium.com/@taitasciore/explicit-props-spreading-in-react-components-acc3eb64394c"><em>https://medium.com/@taitasciore/explicit-props-spreading-in-react-components-acc3eb64394c</em></a></li><li><em>Partial Object Destructuring And Rest Props in React Components With TypeScript:</em><a href="https://medium.com/@taitasciore/partial-object-destructuring-and-rest-props-in-react-components-with-typescript-ffcd84cc8e5"><em> https://medium.com/@taitasciore/partial-object-destructuring-and-rest-props-in-react-components-with-typescript-ffcd84cc8e5</em></a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS6f8kYA6LeQimG9Jx0Kmw.png" /><figcaption>Using destructuring to omit or exclude properties</figcaption></figure><p>Here, TypeScript is smart enough to see that we have destructured some properties, so it is able to narrow down the type of restProps to Omit&lt;SomeComponentProps, ‘someProp’ | ‘anotherProp’ | ‘yetAnotherProp’&gt; or just CommonProps because it knows some properties have been omitted or excluded.</p><p>Notice that this works the same way with arrays. In the example above, we destructured the first element of an array, like ([first = 0, …rest]: number[]). Because of that, rest will contain the remainder (or rest, duh!?) of the array, so this is actually a way of removing the first element from an array.</p><ul><li><strong>Swaping variables:</strong> Remember the ol’ days when you needed to declare a temporary or auxiliary variable in order to swap two variables? Say goodbye to that. Destructuring to the rescue:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Doxv126PYAij1GzBB4sUIw.png" /><figcaption>Using destructuring to swap 2 variables</figcaption></figure><h3>Wrapping Up</h3><p>Today, we learned about destructuring, what it is, and how to use it to <em>unpack</em> values from objects and arrays (and tuples). We started from ground zero and built our way up from there. Finally, we learned about a couple of nice and useful uses for it that are not so common, such as removing properties from an object or elements from an array or swapping 2 variables. In the next article, we will talk about <em>rest parameters</em> with the <em>rest</em> operator, and we will be also taking a look at some <em>tricks</em> you can do with it! Until next time, bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdf7c899768a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partial Object Destructuring And Rest Props in React Components With TypeScript]]></title>
            <link>https://medium.com/@taitasciore/partial-object-destructuring-and-rest-props-in-react-components-with-typescript-ffcd84cc8e5?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcd84cc8e5</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 15:03:53 GMT</pubDate>
            <atom:updated>2023-01-16T15:03:53.198Z</atom:updated>
            <content:encoded><![CDATA[<h4>Safe and concise props spreading in React components with TypeScript</h4><p>In the previous article, I discussed a pattern or technique I like to call <a href="https://medium.com/@taitasciore/explicit-props-spreading-in-react-components-acc3eb64394c">Explicit Props Spreading</a> (EPS). I brought up the fact that spreading the props in React components is not considered a good practice, and I talked about how EPS allows us to remain concise and explicit without sacrificing readability.</p><p>I wanted to write a separate article touching again on the topic of props spreading because there’s a couple more things to be said about it.</p><p>As has been mentioned, when spreading the props, we might be passing extra or unnecessary props to our component. <strong>Props which neither needs nor expects.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nihCT_IxUWEu6-ZEcOZn3A.png" /></figure><p>Here, the TypeScript compiler will be happy and won’t complain as long as we are passing all the required props . The problem here is that we are also passing some unnecessary props to it (‘someProp’ | ‘anotherProp’ | ‘yetAnotherProp’). Nothing bad will happen. The app will behave exactly the same, but we always want to and should be explicit about the props we are passing.</p><h3>Partial Object Destructuring And Rest Props</h3><p>There’s a destructuring <em>trick</em> that allows us to remove properties from an object. We can use this to remove / exclude / omit unwanted properties from our props object to make sure we are only passing the expected ones.</p><p>Using this together with <em>rest parameters</em>, we can spread the props in a safe and concise way. Let me show you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZU7mRwkoAYcGpAqcWd1WXw.png" /><figcaption>Partial Object Destructuring And Rest Props</figcaption></figure><p>What I love about this approach is that TypeScript is smart enough (thank you TS 🙌) to <strong>narrow down and infer the type of </strong><strong>restProps</strong> because it knows some properties have been removed! You can hover the mouse over restProps and you will see the right definition. Basically, the type of restProps is just CommonProps !</p><h4>Related Resources</h4><p>Explicit Props Spreading in React Components: <a href="https://medium.com/@taitasciore/explicit-props-spreading-in-react-components-acc3eb64394c">https://medium.com/@taitasciore/explicit-props-spreading-in-react-components-acc3eb64394c</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcd84cc8e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explicit Props Spreading In React Components]]></title>
            <link>https://medium.com/@taitasciore/explicit-props-spreading-in-react-components-acc3eb64394c?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/acc3eb64394c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 11:34:13 GMT</pubDate>
            <atom:updated>2023-01-16T15:05:32.118Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spreading the props in React components while remaining concise and explicit without sacrificing readability</h4><p><em>Make sure to read this related article as well: Partial Object Destructuring And Rest Props in React Components With TypeScript </em><a href="https://medium.com/@taitasciore/partial-object-destructuring-and-rest-props-in-react-components-with-typescript-ffcd84cc8e5"><em>https://medium.com/@taitasciore/partial-object-destructuring-and-rest-props-in-react-components-with-typescript-ffcd84cc8e5</em></a></p><blockquote>This article assumes knowledge about the spread operator</blockquote><h4>The Problem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVsm6kcoHIORZElNtWOvgw.png" /><figcaption>The Pain Of Forwarding Props</figcaption></figure><p>Does this look familiar? I would be surprised if you haven’t seen or wrote code like this yourself. This can be frustrating because all we want to do is simply pass some props to some component, but we find ourselves repeating ourselves a lot.</p><p>We could take advantage of destructuring to make it slightly less verbose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*jfIVF7cTwN79OuM-oUslFQ.png" /><figcaption>Destructuring + Forwarding Props</figcaption></figure><p>That’s slightly better but still far from ideal. We could then decide to go to the other extreme and have it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fc1qxBvJC-WrYAjAyYMsg.png" /><figcaption>Props Spreading</figcaption></figure><p>It’s also likely that you have seen or wrote code like this yourself. This is considered a <strong>bad practice</strong>.</p><ul><li>We lose <strong>readability</strong> since it’s not clear what props are being passed to the component</li><li>We might be passing extra or unnecessary props that the component does not really need or expect</li></ul><h4>The Best Of Both Worlds</h4><p>We can actually have the best of both worlds: being concise and explicit but without sacrificing readability!</p><p><strong>I humbly introduce you to Explicit Props Spreading</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*rKdImIVaLQMlhDa7qzdJZg.png" /><figcaption>Explicit Props Spreading</figcaption></figure><p>Voila! Granted, it should be noted that for this pattern to work, <strong>the names of the props of both components should match</strong>. Why?</p><p>Let’s see what is happening under the hood when we spread the props in this way. First, we build an inline object taking advantage of the fact that the names of the props match, since in ES6 { someProp: someProp } can be written as just { someProp } . Then, we spread the object, resulting in exactly the same behaviour as the first two images, but writing considerably less code.</p><h4>Wrapping Up</h4><p>Today, we learned about what I like to call <strong>Explicit Props Spreading.</strong> Passing props in this way, we can be a little more concise and less verbose than usual while remaining explicit about what props we are passing, so we are not losing readability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acc3eb64394c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript: Type Inference On Steroids]]></title>
            <link>https://medium.com/@taitasciore/typescript-type-inference-on-steroids-b7c56b6c365d?source=rss-dc7c199417c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7c56b6c365d</guid>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Roberto Tatasciore]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 11:51:57 GMT</pubDate>
            <atom:updated>2023-01-13T11:04:50.035Z</atom:updated>
            <content:encoded><![CDATA[<h4>Esoteric uses of the infer keyword in template string types</h4><p>Recently, I came upon an article here focused on advanced use of TypeScript; and one of the code snippets was making use of a feature that has been available since version 4.8, but which I didn’t know about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeWz1L1Ekvsg4XnopAtanA.jpeg" /></figure><h3>Improved Inference for infer Types in Template String Types</h3><blockquote>TypeScript introduced a way to add extends constraints to infer type variables in conditional types.</blockquote><p>If it’s not clear to you what could be achieved with this change, then I would like to show you an interesting type that I found recently while I was challenging myself defining the <a href="https://medium.com/@taitasciore/arithmetic-operations-in-the-typescript-type-system-because-why-not-cfc2253a93c9">basic arithmetic operations at the type level (addition, subtraction, multiplication, division).</a></p><p>This type makes a number negative!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4694cbbb0a10348c7b417ba4d3f7fa10/href">https://medium.com/media/4694cbbb0a10348c7b417ba4d3f7fa10/href</a></iframe><p>We first define Negative , which, given a number, give us back the <strong>string representation of that negative number.</strong> Then, given a string, ToNumber gives us back the <strong>actual number.</strong> If we use Negative and ToNumber together, we can make a number negative!</p><p>Negative gives us a negative number as a string. This is convenient since we are able to add an extends constraint on N so that we can extract it as a number and not a string! TypeScript will try to parse the type variable to the desired type.</p><p>I hope you enjoyed this article!</p><p>You can also check the <a href="https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#improved-inference-for-infer-types-in-template-string-types">official changelog for version 4.8</a> describing this change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7c56b6c365d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>