<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Brian Schnee</title>
    <description>The latest articles on Forem by Brian Schnee (@brianschnee).</description>
    <link>https://forem.com/brianschnee</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1026221%2Ff9648ef9-62ae-4eac-8f97-5b4d0218b836.jpg</url>
      <title>Forem: Brian Schnee</title>
      <link>https://forem.com/brianschnee</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/brianschnee"/>
    <language>en</language>
    <item>
      <title>The Types You Need - Learning TypeScript</title>
      <dc:creator>Brian Schnee</dc:creator>
      <pubDate>Mon, 13 Mar 2023 17:58:32 +0000</pubDate>
      <link>https://forem.com/brianschnee/the-types-you-need-learning-typescript-185</link>
      <guid>https://forem.com/brianschnee/the-types-you-need-learning-typescript-185</guid>
      <description>&lt;p&gt;This article is a section broken off from my post, &lt;a href="https://dev.to/brianschnee/how-to-learn-and-use-typescript-a-comprehensive-beginners-guide-5l"&gt;How to Learn and Use TypeScript: A Comprehensive Beginner's Guide&lt;/a&gt;. If you haven't read that post yet, I encourage you to start there. You will later be led back to here in the section "The Types You Need."&lt;/p&gt;

&lt;p&gt;In this article, we'll cover the most commonly used types in TypeScript. As we go through them, I've provided links to code examples that you can view on the TypeScript Playground. I recommend opening the examples and seeing the natural inference that takes place. Thank you and enjoy!&lt;/p&gt;




&lt;h2&gt;
  
  
  The Types You Need
&lt;/h2&gt;

&lt;p&gt;By default, TypeScript can understand a great deal about our code without requiring any additional effort on our part. This is called inference. Through inference, TypeScript can often determine the type of a value based on its usage.&lt;/p&gt;

&lt;p&gt;An easy way to appreciate this phenomenon is to hover over your editor’s variables, methods, or function declarations. This can be especially helpful when working with libraries, as hovering over code can reveal valuable insights about data shapes and usage of methods. The best part is that this approach can save time that would otherwise be spent searching through documentation.&lt;/p&gt;

&lt;p&gt;While introducing types, we will see a structure on hover that resembles: let str: string. To read this as if it were English, we would say that "str is of type string" or "str is a string type.” We denote types with the : syntax followed by the type of value we want to store.&lt;/p&gt;

&lt;h3&gt;
  
  
  Type Index
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;number&lt;/li&gt;
&lt;li&gt;string&lt;/li&gt;
&lt;li&gt;boolean&lt;/li&gt;
&lt;li&gt;any&lt;/li&gt;
&lt;li&gt;unknown&lt;/li&gt;
&lt;li&gt;const&lt;/li&gt;
&lt;li&gt;unions&lt;/li&gt;
&lt;li&gt;undefined&lt;/li&gt;
&lt;li&gt;null&lt;/li&gt;
&lt;li&gt;arrays&lt;/li&gt;
&lt;li&gt;objects&lt;/li&gt;
&lt;li&gt;parameters&lt;/li&gt;
&lt;li&gt;return types&lt;/li&gt;
&lt;li&gt;void&lt;/li&gt;
&lt;li&gt;methods&lt;/li&gt;
&lt;li&gt;generics&lt;/li&gt;
&lt;li&gt;custom types&lt;/li&gt;
&lt;li&gt;intersections&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  number
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;number&lt;/code&gt; type represents any number in JavaScript, including negative numbers, NaN, and Infinity.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ty6sjqES--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtp4zw6vdnh6nkra3gr6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ty6sjqES--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtp4zw6vdnh6nkra3gr6.png" alt="Type inference for a number" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/DYUwLgBAdgrgthAvBAjABgNwChYOQJkyA"&gt;Number Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  string
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;string&lt;/code&gt; type represents any collection of characters and can be declared with either single or double quotes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qcHaOMu3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hdz9rdaoxkd8kxaj5ipe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qcHaOMu3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hdz9rdaoxkd8kxaj5ipe.png" alt="Type Inference for a string" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/DYUwLgBAzmBOEF4ICIAWJjAPbINwCgZ4kByAdy1mABMTcg"&gt;String Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  boolean
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;boolean&lt;/code&gt; type refers to true or false.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--XEcghkvk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmq11a3ztxlu9rc8xerk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--XEcghkvk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmq11a3ztxlu9rc8xerk.png" alt="Type inference for a boolean" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/DYUwLgBARg9jwQLwTAJwK4gNwChbyQgDMBDYAZ2yA"&gt;Boolean Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  any
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;any&lt;/code&gt; type typically occurs when a value or variable type cannot be inferred, meaning that the type can be "any" type. When writing code, we usually want to be in an any-less environment. Any doesn't provide type-safety, meaning we operate in JavaScript land.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_meBObcf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a7ow599cxfpqkx7e7gd0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_meBObcf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a7ow599cxfpqkx7e7gd0.png" alt="Type inference for any" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAEzgUwM4GU4Fs1QAWMYA5gBQBuAhgDYhoBci1YAngJSIDeAUIoggIMcWmgB0tOBRr00HXgF8gA"&gt;Any Type Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  unknown
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;unknown&lt;/code&gt; type is a safer, more descriptive way to define when you don’t know the type of value. It's a great choice instead of using &lt;code&gt;any&lt;/code&gt; in specific scenarios. It's safer because TypeScript will force us to perform a runtime check or type assertion before the value can be used. Although this seems annoying, it allows us to maintain type safety. A typical use case of unknown could be typing the return of an API call.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mQrBlBgi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vscsd3h7631a86u94cyc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mQrBlBgi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vscsd3h7631a86u94cyc.png" alt="making a request" width="800" height="283"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBATgUwgB3BBAuGBXMBrMEAdzBgF4YAzBKYACwAoByOqKZCDAei4QA8AhgFtkAGwQA6UEK4BGJgEoA3EA"&gt;Unknown Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  const
&lt;/h3&gt;

&lt;p&gt;When we declare a variable with the &lt;code&gt;const&lt;/code&gt; keyword, the value is considered &lt;code&gt;Readonly&lt;/code&gt;, meaning the value can never be mutated. In TypeScript, this changes the type of a value from its &lt;code&gt;primitive type&lt;/code&gt; to what’s referred to as a &lt;code&gt;literal type&lt;/code&gt;, which means that the type of a value is just that value.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note that const only has the &lt;code&gt;literal type&lt;/code&gt; effect for JavaScript primitives (number, boolean, string, symbol, bigint, undefined, and null). This is because the value assigned to the variable cannot be changed without reassignment, unlike &lt;code&gt;arrays&lt;/code&gt; or &lt;code&gt;objects&lt;/code&gt; that can gain new properties or elements without being reassigned.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oLlbYoUQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avkeygemvsceow4lpmqu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oLlbYoUQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avkeygemvsceow4lpmqu.png" alt="Type Inference for const" width="800" height="283"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBNBOMC8MBEB3AFgQ1gExBgE8QBXGAWwFNswYBJAcgpmxgBsBLKK+bdmFCIAHKqiA"&gt;Const Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  unions
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;|&lt;/code&gt; operator specifies a &lt;code&gt;union&lt;/code&gt; of types. A union allows a variable to hold values of different types. &lt;em&gt;It's possible to chain together unions of types by using multiple unions in succession.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZcK8Uu-0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/188idxagc2sc4yqti3o6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZcK8Uu-0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/188idxagc2sc4yqti3o6.png" alt="union types" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/DYUwLgBAbghsCuIBcEB28C2AjEAnCAPhAM5i4CWqA5gNwBQsCIEAvBAIwAM9jirEAIjAhUAmkA"&gt;Union Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  undefined
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;undefined&lt;/code&gt; type occurs when we explicitly define the behavior. We can type something as undefined, but a more common use case happens when we use the optional syntax &lt;code&gt;?&lt;/code&gt; for function parameters or properties of an object type. Defining an optional type will create a union of the specified type and undefined.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4rE1xvmc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/48o04yxsqk17j24decpb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4rE1xvmc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/48o04yxsqk17j24decpb.png" alt="Optional Parameters" width="800" height="330"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABABwE4zFAcgQwLYCmAFMDKgM5QBcil6YA5gDSIA2OlA-DXRgwJSIA3gChEiEQF8gA"&gt;Undefined Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  null
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;null&lt;/code&gt; type can be used in a few different places, but it's most commonly used in a union as the return type of a function or to store a variable’s default value that may change later.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--aKrRH8Xi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dsmfo6chmnscoovquq73.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--aKrRH8Xi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dsmfo6chmnscoovquq73.png" alt="String or null union type" width="800" height="356"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/DYUwLgBAbghsCuIBcEDOYBOBLAdgcwgB8Id5hgIBeEs4AbgCgGsAzACk0QEoIBvBiNDiIqEAEQALEOQD2YhgF8gA"&gt;Null Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  arrays
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;array&lt;/code&gt; type houses a list of elements of a specific type. Remember that union types are types themselves, which means that if you specify an array of union types, the array can hold multiple kinds of elements.&lt;/p&gt;

&lt;p&gt;Two different kinds of syntax can be used to define an array type. The first way and way in which you'll see arrays denoted is to use square brackets &lt;code&gt;[]&lt;/code&gt;. The second way is to define a &lt;code&gt;type constructor&lt;/code&gt; for arrays, &lt;code&gt;Array&amp;lt;number&amp;gt;&lt;/code&gt;, which we will cover later with generics.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--huADSRdt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fwxftwmh5gvzdj6fdjz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--huADSRdt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fwxftwmh5gvzdj6fdjz.png" alt="Array of a union between a string and number" width="800" height="283"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDA2gIigCwJZgDmmANDAIwC6A3EA"&gt;Array Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  objects
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;object&lt;/code&gt; type is a collection of types. Unlike unions, object types are precise declarations and require using the property keys you define and the correct type of values they store. Object types can house as many properties and different kinds of types as you would like, including other object types. You can create an object type by using curly braces &lt;code&gt;{}&lt;/code&gt; and adding a property name and the type of the value in the structure of a regular JavaScript object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pmOWkmtK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1me0q7xa26yn87ne9gl1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pmOWkmtK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1me0q7xa26yn87ne9gl1.png" alt="Object type with a firstName and lastName property typed as strings" width="800" height="330"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBADgUwE4XALhgbxgMwJYpQByAhgLYIbRJ5gDmANDADYnSkVVQ30wC+MALxYAUDFwF25SjABEAIRAAjWQzEs2xaRlkBhEABNkskXyA"&gt;Object Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  parameters
&lt;/h3&gt;

&lt;p&gt;As seen before, you will want to type the parameters in a function. This is super helpful for self-documenting and minimally validating the inputs of a function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--26gZcDec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ec8hvcu930t0zpr6lvw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--26gZcDec--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ec8hvcu930t0zpr6lvw.png" alt="Typing function parameters" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAWxAG1gBzQTwBQCGAXImCMgEYCmATgDSIUlmW0CUiA3gFCKI1UoIGkgKIAVIwDc3AL5A"&gt;Parameter Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  return types
&lt;/h3&gt;

&lt;p&gt;Return types can be automatically inferred in typescript. If you take the example from the parameters section, TypeScript already knows the return value will be a number. Let’s switch up the type of one of the variables and add an explicit return type to state our intentions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bBzAPz5Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf78iuznz1q0472mkoge.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bBzAPz5Y--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf78iuznz1q0472mkoge.png" alt="Return type of function" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAWxAG1gBzQTwBQCGAXImCMgEYCmATgDSIUkDOUNMYA5gJQlmW1EAbwBQiRDSpQQNJAUQAqRADly1GngrcA3CIC+QA"&gt;Return Code Example&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note that we had to convert &lt;code&gt;b&lt;/code&gt; from a &lt;code&gt;string&lt;/code&gt; to a &lt;code&gt;number&lt;/code&gt;; otherwise, TypeScript would tell us something is wrong.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  void
&lt;/h3&gt;

&lt;p&gt;A function that does not return a value is said to return &lt;code&gt;void&lt;/code&gt;. This is automatically inferred if a function does not include the &lt;code&gt;return&lt;/code&gt; keyword. However, typing the return can give us type safety within the function, ensuring we aren't unintentionally returning.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5jTuv2ot--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kmjbtf6eoz722wzv1umj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5jTuv2ot--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kmjbtf6eoz722wzv1umj.png" alt="Void function return" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABABwE4zFAyiAtgCgEMAuRMPAIwFNUAaRC083a1ASlIDc4YATRAN4AoRIggIAznAA2VAHTS4AcyKIA1AzYBuIQF8gA"&gt;Void Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  methods
&lt;/h3&gt;

&lt;p&gt;Creating &lt;code&gt;method&lt;/code&gt; types can define the shape of a function's inputs and return. In the example below, we construct a type for a method belonging to an object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cghQJ7-0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj3xec3r5fg4z46ot7nt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cghQJ7-0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj3xec3r5fg4z46ot7nt.png" alt="Example of a method being types" width="800" height="459"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBMCGUBcMDeAoGMzwLYFMVoAnASzAHMAaTGCAB33gGsUAKCEAVzABMioZSgEoYAXgB8MAG4hSvdAF9xaWjgIoA5ABVSuTTSwMmrGB259RkuOE4AbfADo7ICuZ69hS9OgRRHxixsmgQgAO6awgDcQA"&gt;Method Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  generics
&lt;/h3&gt;

&lt;p&gt;In TypeScript, generics are a way to parameterize types and functions to work with any type instead of a specific one. It's a way to define the structure of a type while being agnostic to the underlying operations of that structure. Generics are commonly seen throughout usage with external JavaScript libraries, and they are powerful but tricky to understand and read errors from.&lt;/p&gt;

&lt;p&gt;For our example, I will show you the instance mentioned in the Arrays section where we use the Array constructor. The Array constructor allows us to pass in a type that will comprise the elements of the array.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;To learn how to construct generic types, visit &lt;a href="https://www.typescriptlang.org/docs/handbook/2/generics.html"&gt;Generics&lt;/a&gt;. We will skip over their creation because they aren't necessary when starting. It is important to see the constructors for these generic types, like in the example below.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AcN3kZ3i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yudr3sauupz6kju2we1f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AcN3kZ3i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yudr3sauupz6kju2we1f.png" alt="Array constructor" width="800" height="283"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBNBOBLMBzCAuGBBe8CGAngDwLIoB8MAvDANoBEpq9ANDPQKYA2HAth2CgR6AXQDcQA"&gt;Generics Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  custom types
&lt;/h3&gt;

&lt;p&gt;Creating your own types is valuable when you want to add semantic meaning to a type, decrease the size of a type declaration, and export a type to be used throughout your application. Custom types typically follow the Pascal Case naming convention where the first letter of every word is capitalized, including the very first word, "MyCustomType."&lt;/p&gt;

&lt;h4&gt;
  
  
  type keyword
&lt;/h4&gt;

&lt;p&gt;We can declare our own types in TypeScript using the &lt;code&gt;type&lt;/code&gt; keyword, followed by a name and set equal to any type we previously learned.&lt;/p&gt;

&lt;p&gt;In the Objects section, we created a type inline. Let's see what it would look like to abstract an object type.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8coVkVpr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9r6ro609swise0wj894r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8coVkVpr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9r6ro609swise0wj894r.png" alt="Using the type Keyword" width="800" height="510"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAqgzhATlAvFA3gKClCBbAQwEsAbALijmESIDsBzAGmygFcFFaC8IKqaGzHGAJw4AdwD2iACZ9qdepgC+mTAGNJtKlABGk3RXhJUGFvmLkoAIn26AAvUKkAdJrzWhbDlx4VbBpoySJ4sImJSsv7hEtIy1ipAA"&gt;Type Keyword Code Example&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Remember that the curly braces indicate an object type. We can set a type equal to anything, such as primitives, unions, objects, arrays, etc.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  interfaces
&lt;/h4&gt;

&lt;p&gt;Using interfaces acts very similar to using the type keyword. They both generate the same thing, but interfaces have a few quirks. Some say it is preference what you use, but due to the potential performance implications, it is generally advised to use the type keyword unless you need to use the &lt;code&gt;extends&lt;/code&gt; keyword. The extends keyword is used to inherit properties and methods from another type, and it’s exactly like how inheritance works in Object-Oriented Programming. Another distinction between interfaces and the type keyword is that interfaces must hold Object types, and the type keyword can hold anything. Because of this, interfaces do not use an equal sign. &lt;/p&gt;

&lt;p&gt;Here is an example of an interface using the extends keyword.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---LSZVl1---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96v1yqtubsd3gki81reu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---LSZVl1---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96v1yqtubsd3gki81reu.png" alt="Typing with interfaces" width="800" height="587"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlkBnABwgWAlIC4ywpQBzAGmORwhBbAAsAkiABiECGAYgArpgBG0QgF9ChUJFiIUAZRBwA1iggAPSCAAmpNBmx4iJAG48A9pmfT6yOc+fc4IZVUEZxBSMGRguSg4Bl0DFABeAk4KKhpPACJSPUMMjhJuXgFhMQkGABZ85CcQV3dPJmkIZSA"&gt;Interface Code Example&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;When creating any object-related type, you can separate key-value pairs with commas, semi-colons, or nothing, as long as they sit on their own lines.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  intersections
&lt;/h3&gt;

&lt;p&gt;An &lt;code&gt;intersection&lt;/code&gt; defines a combination of multiple types. Unlike a union, where we specify a type as one type or another, an intersection will combine the properties of various object types into a brand-new type. Meaning you must satisfy the behavior of both types combined.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--qFb6tJq5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6awh7k1gnz8ebvizlihc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--qFb6tJq5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6awh7k1gnz8ebvizlihc.png" alt="Intersection of types" width="800" height="459"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAqgzhATlAvFA3lAdgQwLYQBcUcwiAllgOYA0U5AJsaRdVAL4DcAUKJFACUA9gBtoaTIlFEoAcgCCDPJVlQAPnPhJVXXuGhbEAdXLAAFsLGpYCZADJB0ntwDGQrKSgBXW8UMnzS3EMbihsfBlZACEKHCxZGlD6JjkcAGYRAGsAKzgGAA4AFiwChKSpMWJZQ1ludiA"&gt;Intersection Code Example&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QM7Tna45--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmuleo5konfj3s6dwrow.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QM7Tna45--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmuleo5konfj3s6dwrow.jpg" alt='"Fin", end of article' width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You made it! Thank you for spending the time to read what I wrote. If you found this article helpful and enjoyed learning about TypeScript, consider sharing it with others. Feedback and suggestions for future topics are always welcome. &lt;/p&gt;

&lt;p&gt;For further TypeScript exploration, I recommend heading back to my blog post &lt;a href="https://dev.to/brianschnee/how-to-learn-and-use-typescript-a-comprehensive-beginners-guide-5l"&gt;How to Learn and Use TypeScript: A Comprehensive Beginner's Guide&lt;/a&gt; where you'll next learn about how to benefit from your coding environment, read error messages and use TypeScript in your projects.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to Learn and Use TypeScript: A Comprehensive Beginner's Guide</title>
      <dc:creator>Brian Schnee</dc:creator>
      <pubDate>Fri, 10 Mar 2023 19:04:55 +0000</pubDate>
      <link>https://forem.com/brianschnee/how-to-learn-and-use-typescript-a-comprehensive-beginners-guide-5l</link>
      <guid>https://forem.com/brianschnee/how-to-learn-and-use-typescript-a-comprehensive-beginners-guide-5l</guid>
      <description>&lt;p&gt;In this article, I will provide tools and a mental framework to help you effectively learn and work with TypeScript. I will show you that learning TypeScript from a JavaScript background is more manageable than it may seem. To achieve this, we will begin by understanding the foundational types, but with a slightly different approach emphasizing practical application. Finally, I will share tips and tricks I have picked up through experience that you won't find anywhere else.&lt;/p&gt;

&lt;p&gt;This is a comprehensive resource aimed to be the last resource you will ever need to start using TypeScript. As such, I recommend breaking up your time reading this article into chunks. The following sections will provide information I wish I had known when first learning to use TypeScript.&lt;/p&gt;

&lt;p&gt;Please enjoy!&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;How To Learn TypeScript&lt;/li&gt;
&lt;li&gt;Understanding Type Safety&lt;/li&gt;
&lt;li&gt;The Types You Need&lt;/li&gt;
&lt;li&gt;Benefiting From Your Coding Environment&lt;/li&gt;
&lt;li&gt;How to Read Error Messages&lt;/li&gt;
&lt;li&gt;Using TypeScript in a Project Environment&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  How To Learn TypeScript
&lt;/h2&gt;

&lt;p&gt;Mastering TypeScript requires more than just learning its syntax. Knowing the types is a meaningful step, but most importantly, it is how to understand the patterns of our code. Please be aware that TypeScript is a development aid but should not be seen as the sole code we are writing. Most of our coding is still plain old JavaScript with stated expectations.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: All JavaScript is valid TypeScript. Once you transpile your code, all of your TypeScript will become JavaScript. More on this later.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Understanding Type Safety
&lt;/h2&gt;

&lt;p&gt;TypeScript prevents us from assigning values of the wrong type to a variable; this is called &lt;code&gt;type safety&lt;/code&gt;. In TypeScript, we can declare the type of a variable, which helps to ensure that the variable only holds values of that specific type throughout the lifetime of our application.&lt;/p&gt;

&lt;p&gt;By enforcing type safety, TypeScript can catch potential errors early in the development process, leading to more reliable and robust code. This also means that, compared to JavaScript, we can often prevent runtime errors that users may have otherwise encountered.&lt;/p&gt;

&lt;p&gt;The types we'll cover will be familiar terms, such as &lt;code&gt;number&lt;/code&gt;, &lt;code&gt;string&lt;/code&gt;, &lt;code&gt;boolean&lt;/code&gt;, &lt;code&gt;array&lt;/code&gt;, and &lt;code&gt;object&lt;/code&gt;. The critical difference is that TypeScript provides a way to ensure the validity of our values in real-time. In contrast, JavaScript lacks such a mechanism, making it tedious and sometimes difficult to guarantee the correctness of values without writing conditions and boilerplate code.&lt;/p&gt;

&lt;p&gt;Take a look at the JavaScript example below. To verify that every element of the numbers array is a number, we need to add a check that runs during every iteration.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0o3bhgslxmkx8tqbh1vj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0o3bhgslxmkx8tqbh1vj.png" alt="JavaScript boilerplate"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Although that wasn't too bad, did you notice that the numbers parameter was never validated as an array? It's easy to miss potential problems in our code.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Let's see how we can avoid manually testing edge cases in the next section.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  The Types You Need
&lt;/h2&gt;

&lt;p&gt;I've decided to create a separate article for this section, so those who feel comfortable with the material can move on easily. And, for those who want to revisit the recommended types later, it'll now be easier to explore.&lt;/p&gt;

&lt;p&gt;If you're new to TypeScript or want a refresher on the most commonly used types, head over to &lt;a href="https://dev.to/brianschnee/the-types-you-need-learning-typescript-185"&gt;The Types You Need&lt;/a&gt;, where we'll continue from where we left off and learn about the following types: &lt;code&gt;number&lt;/code&gt;, &lt;code&gt;string&lt;/code&gt;, &lt;code&gt;boolean&lt;/code&gt;, &lt;code&gt;any&lt;/code&gt;, &lt;code&gt;unknown&lt;/code&gt;, &lt;code&gt;const&lt;/code&gt;, &lt;code&gt;unions&lt;/code&gt;, &lt;code&gt;undefined&lt;/code&gt;, &lt;code&gt;null&lt;/code&gt;, &lt;code&gt;arrays&lt;/code&gt;, &lt;code&gt;objects&lt;/code&gt;, &lt;code&gt;parameters&lt;/code&gt;, &lt;code&gt;return types&lt;/code&gt;, &lt;code&gt;void&lt;/code&gt;, &lt;code&gt;methods&lt;/code&gt;, &lt;code&gt;generics&lt;/code&gt;, &lt;code&gt;custom types&lt;/code&gt; and &lt;code&gt;intersections&lt;/code&gt;. From there, you will be led back to this article where I encourage you to continue learning. Thank you!&lt;/p&gt;




&lt;h2&gt;
  
  
  Benefiting From Your Coding Environment
&lt;/h2&gt;

&lt;p&gt;TypeScript offers more than just error detection and correction. By leveraging TypeScript's type system and writing clean, reusable code, you can build an environment that helps you write better code. TypeScript can identify potential problem areas in your code and suggest solutions, allowing you to avoid errors and write code that is easier to maintain.&lt;/p&gt;

&lt;h3&gt;
  
  
  Program Predictive Behavior
&lt;/h3&gt;

&lt;p&gt;To make the most of TypeScript, it's essential to define the behavior you want to use and follow it throughout development. By extracting repeating code into types and clearly stating your intentions for variables and returns, TypeScript can help guide you toward the right solution. With TypeScript's help, you can write correct, easy-to-read, and maintainable code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let TypeScript Guide You
&lt;/h3&gt;

&lt;p&gt;TypeScript's powerful type system provides you with immediate feedback on potential issues in your code. If you try to assign a value of the wrong type to a variable, TypeScript will generate an error message and show a squiggly line under the offending code. Following TypeScript’s guidance can make you a more efficient and productive developer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Improved Developer Experience
&lt;/h3&gt;

&lt;p&gt;TypeScript significantly improves your developer experience by providing tools that help you write better code faster. Its editor integration offers intelligent code completion, navigation, and refactoring, allowing you to write more confidently and accurately. TypeScript's strict type-checking identifies potential issues in your code early on, giving you more time to build new features instead of fixing bugs. This type of safety also works across your entire project, ensuring consistency and reducing the risk of errors. Additionally, TypeScript's support for modern ECMAScript features allows you to use the latest language features while maintaining compatibility with older browsers.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to Read Error Messages
&lt;/h2&gt;

&lt;p&gt;Understanding error messages in TypeScript can be challenging, but with practice, it becomes easier. To begin with, it is crucial to understand the expectations of the code you use, which means knowing the expected types of variables, functions, and values.&lt;/p&gt;

&lt;p&gt;When you encounter a type error, it can happen in one of two ways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When you attempt to use a variable, function, or value in a way that breaks its type contract. &lt;/li&gt;
&lt;li&gt;When TypeScript needs more information about what you're trying to do to be confident about the behavior. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;TypeScript will provide an error message to help you understand both cases’ issues.&lt;/p&gt;

&lt;p&gt;To become proficient at understanding error messages, you need to become familiar with the typical patterns of errors that occur. This familiarity will help you recognize pitfalls as they happen, making it easier to debug your code.&lt;/p&gt;

&lt;p&gt;For better assistance in reading error messages, you can download the VSCode extension &lt;a href="https://marketplace.visualstudio.com/items?itemName=mattpocock.ts-error-translator" rel="noopener noreferrer"&gt;Total TypeScript&lt;/a&gt; by Matt Pocock. This extension includes an error translator that converts TypeScript error messages into a more human-readable format.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common Errors and Why They Happen
&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;While reading through this section, I encourage you to click on the example code and try to solve the type errors. You will have succeeded when the error messages go away. Good Luck!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Type 'x' is not assignable to type 'y'&lt;/code&gt;: This error occurs when you try to assign a value of a different type to a variable than the type the variable was defined with.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjg0v2epfrzifae48rts0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjg0v2epfrzifae48rts0.png" alt="Example of the Error Message: Type 'x' is not assignable to type 'y'"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/DYUwLgBAzmBOBc04EsB2BzCBeCAiAFsrgNwBQMs2EcAriMUA" rel="noopener noreferrer"&gt;Example of the Error&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Solution: Change your code to follow or redefine the type contract.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;code&gt;Property 'x' does not exist on type 'y'&lt;/code&gt;: This error occurs when you try to access a property that does not exist on an object.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffot8qesku85a9x2foixo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffot8qesku85a9x2foixo.png" alt="Example of the Error Message: Property 'x' does not exist on type 'y'"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBADgUwE4XALhgbxmAhgWwQ2iQEswBzGAXxgF4sAoGHAomAIgCtcwEPGtRo0QpwAOlwUEQA" rel="noopener noreferrer"&gt;Example of the Error&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Solution: The error message will include the shape of the object you are trying to access a property from. Read the definition and make sure to use properties that exist within the type.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Tip: When you type '.' on an object, TypeScript will show you the methods and properties that belong to the object.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;code&gt;Cannot find name 'x'&lt;/code&gt;: This error occurs when you try to use a variable or name that has not been declared or is not accessible in the current scope.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsbaely2ydpj5mrbaxtsf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsbaely2ydpj5mrbaxtsf.png" alt="Example of the Error Message: Cannot find name 'x'"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgziA2CmB00QHMAUAHWAnKYCUA3EA" rel="noopener noreferrer"&gt;Example of the Error&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Solution: Define the variable you are trying to use, consider the scope, and check your spelling.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;code&gt;Parameter 'x' implicitly has an 'any' type&lt;/code&gt;: This error occurs when you do not explicitly declare the type of a function parameter and TypeScript cannot infer it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdojvzy90o0i752ja5wa6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdojvzy90o0i752ja5wa6.png" alt="Example of the Error Message: Parameter 'x' implicitly has an 'any' type"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?ssl=3&amp;amp;ssc=2&amp;amp;pln=1&amp;amp;pc=1#code/GYVwdgxgLglg9mABABwE4zFAFANwIYA2IApgJSIDeAUIohAgM5wHEB0BcA5roSaQNxUAvkA" rel="noopener noreferrer"&gt;Example of the Error&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Solution: TypeScript would like to know more about the usage of your variable. In this case, create a type based on what behavior you want. You can type an element explicitly as 'any’, but it is generally unadvised for most cases.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;code&gt;The left-hand side of an arithmetic operation must be of type 'any’, 'number', 'bigint' or an enum type&lt;/code&gt;: This error occurs when you try to perform an arithmetic operation on a value that is not a number or a BigInt.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F41ppb8fveewzh40eq3rt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F41ppb8fveewzh40eq3rt.png" alt="Example of the Error Message: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBNBOMC8MBECCWYDmqDcAUKJLGAK4C2yMArEeNDAG4CGANmQKbUIwBUMchTxA" rel="noopener noreferrer"&gt;Example of the Error&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Solution: Verify that you are performing proper operations for each type. In certain cases, you can cast a value to the right type.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;code&gt;Object is possibly 'null' or 'undefined'&lt;/code&gt;: This error occurs when trying to access a property or method on an object that may be null or undefined.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiwyom3smw51b1xx5j6fi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiwyom3smw51b1xx5j6fi.png" alt="Example of the Error Message: Object is possibly 'null' or 'undefined'"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBAFiARoglgUwjAvDAFGAQwFs0AuGaAJxTAHMAaeJVDAfnKptoG0BdASmwA+GAG8AUDBihIIADZoAdHJC1cAAwAkowiQC+8Apm0Jk6CMrR0ocA6ZYX1-cXqA" rel="noopener noreferrer"&gt;Example of the Error&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Solution: Add type checking before you use properties on a potentially null or undefined object through conditionals.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Tip: You can alternatively use JavaScript's &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noopener noreferrer"&gt;optional chaining operator ?.&lt;/a&gt;, or in certain cases, TypeScript's &lt;a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator" rel="noopener noreferrer"&gt;Non-null assertion operator !&lt;/a&gt; (use with caution) to verify that an object is neither undefined nor null and keep your code concise.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Using TypeScript in a Project Environment
&lt;/h2&gt;

&lt;p&gt;Now that we have introduced a collection of types, using TypeScript to our benefit and standard errors, let's learn how to use TypeScript within a project environment. Throughout this section, I will show you how to use TypeScript within a Node.js environment.&lt;/p&gt;




&lt;h3&gt;
  
  
  Basic TypeScript Project Structure
&lt;/h3&gt;

&lt;p&gt;In TypeScript projects, keeping all your code in a directory called src located at the root of your project is typical. Similarly, all files and folders related to your project's creation and configuration should be kept at the root level. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node_modules/
src/
   |_ all your `.ts` files in here
.gitignore
package-lock.json
package.json
tsconfig.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  What do I do with the tsconfig.json?
&lt;/h3&gt;

&lt;p&gt;When I first began using TypeScript, I struggled to find comprehensive guidance on structuring my tsconfig.json file. This file defines the rules that our TypeScript code should adhere to, including the code it should support, things to check for, how it should be transpiled,  and where it should be transpiled.&lt;/p&gt;

&lt;p&gt;As a beginner, I suggest keeping it simple. When you continue to work with TypeScript, you will find rules that match your needs. For now, don't stress over it; there are no perfect rules.&lt;/p&gt;

&lt;p&gt;The easiest option is to use the following command to generate a template for you.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;tsc &lt;span class="nt"&gt;--init&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;If you do not have TypeScript globally installed, use &lt;code&gt;npx tsc --init&lt;/code&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This command will generate a &lt;code&gt;tsconfig.json&lt;/code&gt; file with potential rules that can be turned on (by uncommenting). Due to the number of rules, I find it easier to work from a less daunting template that allows you to find and add rules iteratively. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Visit &lt;a href="https://www.typescriptlang.org/tsconfig" rel="noopener noreferrer"&gt;Compiler Options&lt;/a&gt;&lt;/em&gt; to find rules that match your needs.&lt;/p&gt;

&lt;h4&gt;
  
  
  Starter Template
&lt;/h4&gt;

&lt;p&gt;Let's replace the contents of the &lt;code&gt;tsconfig.json&lt;/code&gt; file with our own rules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tsconfig.json&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"compilerOptions"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"target"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"es6"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"module"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"commonjs"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"strict"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"esModuleInterop"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"include"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"src/**/*"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"exclude"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"node_modules"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  How to Run Your Code?
&lt;/h3&gt;

&lt;p&gt;At some point, our TypeScript code must &lt;code&gt;transpile&lt;/code&gt; into JavaScript to be run and understood by node or our browser. Transpilation is when one language is translated into another.&lt;/p&gt;

&lt;p&gt;Usually, TypeScript tutorials start by showing us how to &lt;a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html" rel="noopener noreferrer"&gt;transpile our code with tsc&lt;/a&gt;, but I will be providing other options that I tend to prefer. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: There are many different ways to run TypeScript; what you choose will primarily be based on performance within your workspace.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Using node
&lt;/h4&gt;

&lt;p&gt;The easiest way to execute your code is by running the &lt;code&gt;node&lt;/code&gt; command followed by the root file of your project. This command will both transpile and execute your code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node src/index.ts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note: You can install the &lt;code&gt;nodemon&lt;/code&gt; package to automatically re-execute on change. However, we will cover how to use ts-node-dev, which is what I prefer.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Using ts-node-dev
&lt;/h4&gt;

&lt;p&gt;I recommend using this method for most of your projects, and it’s easy to set up and more performant.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;There are ways to make using nodemon performant, but the steps are far more involved than the following:&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;First, install &lt;code&gt;ts-node-dev&lt;/code&gt; as a devDependency.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm i &lt;span class="nt"&gt;-D&lt;/span&gt; ts-node-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the following to your &lt;code&gt;package.json&lt;/code&gt; scripts. &lt;em&gt;The &lt;code&gt;--respawn&lt;/code&gt; flag will re-transpile and execute your project on save.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// pacakage.json
"scripts": {
   "dev": "ts-node-dev --respawn src/index.ts"
},
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run your project&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Using TypesSript in your Existing Projects
&lt;/h3&gt;

&lt;p&gt;To start working in a node environment with TypeScript, it's essential to understand how declaration files work. As your project grows and you install dependencies, TypeScript will need type information for each dependency to ensure you can use library code in a type-safe manner. Installing type declarations for your dependencies is usually straightforward: use the following command for each dependency, as the declarations are often already available. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;We use the &lt;code&gt;@types/&lt;/code&gt; followed by the dependency’s name.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm i &lt;span class="nt"&gt;-D&lt;/span&gt; @types/express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note: Remember to install all TypeScript-related tools as devDependencies.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Tips For Migration
&lt;/h3&gt;

&lt;p&gt;If you would like to use TypeScript in an existing project, it can be tricky to convert your project from a non-type-safe environment to one that is. I recommend making incremental changes in your code base that allow you to increase your TypeScript coverage in your project slowly. Tackle your project in chunks, following our steps for setting up TypeScript and changing &lt;code&gt;.js&lt;/code&gt; files to &lt;code&gt;.ts&lt;/code&gt; (&lt;code&gt;.jsx&lt;/code&gt; to &lt;code&gt;.tsx&lt;/code&gt; in React codebases). After converting the files, you will most likely encounter a handful of "errors" that must be corrected. All this is, is TypeScript wanting you to create contracts and state expectations about your code. &lt;/p&gt;

&lt;p&gt;Best of luck, and you will find resources in the conclusion that will help you if you get stuck.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftmuleo5konfj3s6dwrow.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftmuleo5konfj3s6dwrow.jpg" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You made it! Thank you for spending the time to read what I wrote. If you found this article helpful and enjoyed learning about TypeScript, consider sharing it with others. Feedback and suggestions for future topics are always welcome. &lt;/p&gt;

&lt;p&gt;For further TypeScript exploration, I recommend checking out the &lt;a href="https://www.typescriptlang.org/docs/handbook/intro.html" rel="noopener noreferrer"&gt;TypeScript Handbook&lt;/a&gt; and Matt Pocock's free beginner tutorials at &lt;a href="https://www.totaltypescript.com/tutorials/beginners-typescript" rel="noopener noreferrer"&gt;Total TypeScript&lt;/a&gt;. However, you should now have enough exposure to start using TypeScript in your projects. &lt;/p&gt;

&lt;p&gt;Sometimes errors may feel overwhelming. I recommend joining the &lt;a href="https://discord.gg/typescript" rel="noopener noreferrer"&gt;TypeScript Community Discord Server&lt;/a&gt; for help with anything and everything TypeScript.&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Rust's most unique memory management features explained - Ownership and Borrowing</title>
      <dc:creator>Brian Schnee</dc:creator>
      <pubDate>Wed, 15 Feb 2023 16:13:06 +0000</pubDate>
      <link>https://forem.com/brianschnee/rusts-most-unique-memory-management-features-explained-ownership-and-borrowing-49g5</link>
      <guid>https://forem.com/brianschnee/rusts-most-unique-memory-management-features-explained-ownership-and-borrowing-49g5</guid>
      <description>&lt;p&gt;Before jumping into what makes Rust's memory management system unique, we must define the terms we are working with. After, we can establish examples that help us understand this tricky subject. We will cover various topics to solidify your understanding of some of Rust's core concepts.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Memory&lt;/li&gt;
&lt;li&gt;Memory Safety&lt;/li&gt;
&lt;li&gt;Ownership&lt;/li&gt;
&lt;li&gt;Borrowing&lt;/li&gt;
&lt;li&gt;Mutable vs. Immutable Values&lt;/li&gt;
&lt;li&gt;Rules of Ownership&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What is Memory?
&lt;/h2&gt;

&lt;p&gt;Memory is comprised of &lt;code&gt;addresses&lt;/code&gt; and &lt;code&gt;values&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;An &lt;code&gt;address&lt;/code&gt; is a location on your computer used to find a piece of data.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;value&lt;/code&gt; is the data stored at a location on your computer.&lt;/p&gt;

&lt;p&gt;Working with memory can be dangerous, so before you start accessing random memory addresses on your computer, let's talk about those dangers and how Rust tries to mitigate them.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Memory Safety?
&lt;/h2&gt;

&lt;p&gt;Working with memory is a core aspect of computing, allowing us to perform a series of tasks we refer to as our program. However, working with memory introduces a variety of pitfalls that modern languages like Rust intend to protect us from. &lt;/p&gt;

&lt;p&gt;Think of it like knocking on someone's door that doesn't expect you to be there. Not everyone is as friendly as they seem, and this is the case for accessing and attempting to mutate values stored at foreign memory addresses. &lt;/p&gt;

&lt;p&gt;Because of the bugs and errors this can produce, languages like Rust have safe strategies for accessing data in memory. Higher-level programming languages opt to shield programmers from these afflictions completely. Although this may seem a wiser option, lower-level languages enable programmers to take agency of memory. When done right, the outcome is a more efficient and performant program. &lt;/p&gt;

&lt;p&gt;Can you say 🔥&lt;em&gt;&lt;strong&gt;BLAZINGLY FAST&lt;/strong&gt;&lt;/em&gt;🔥 with me?&lt;/p&gt;

&lt;p&gt;Now, let's &lt;em&gt;Segway&lt;/em&gt; into Rust's solution...&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F816u685c2amh25coeru8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F816u685c2amh25coeru8.jpg" alt="Paul Blart segwaying into the next section of this blog"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  What is Ownership?
&lt;/h2&gt;

&lt;p&gt;In Rust, &lt;code&gt;ownership&lt;/code&gt; is used to manage memory safely. An &lt;code&gt;owner&lt;/code&gt; is a piece of code, object, or variable with complete control over the data it holds. When a variable is declared, a memory address is given to that variable. It is considered the owner of that address until it is no longer needed or ownership is transferred. This means that at some point in our program, Rust will free the memory we were using without needing to deallocate like we may have to in other languages manually. In Rust, transferring ownership is called a &lt;code&gt;move&lt;/code&gt;. When ownership of a value is moved, we can no longer access the value from the first memory address.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hello"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// ownership of `s1` has moved to `s2`&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{s1}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="cm"&gt;/* this will result in an error, because 
                        `s1` has moved to `s2` */&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before jumping into the ownership rules, let's define a few more terms.&lt;/p&gt;




&lt;h2&gt;
  
  
  What is Borrowing?
&lt;/h2&gt;

&lt;p&gt;If a value can only have one owner, we need a way to allow other pieces of code to access the data stored in memory addresses without taking ownership. We refer to this as &lt;code&gt;borrowing&lt;/code&gt;. Borrowing enables us to create a reference to another piece of data without taking responsibility for the memory. A &lt;code&gt;reference&lt;/code&gt; in Rust, written with the &lt;code&gt;&amp;amp;&lt;/code&gt; symbol, refers to a memory address that holds a value. Borrowing also ensures that you are operating on non-null, valid memory addresses.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello, world"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;ref_to_x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="cm"&gt;/* `ref_to_x` borrows the value 
                          stored in `x` */&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{ref_to_x}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// prints "Hello, world"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Borrowing vs. Moving values in functions
&lt;/h3&gt;

&lt;p&gt;Certain behaviors of ownership can come unnatural to new users of Rust. For example, ownership is &lt;code&gt;moved&lt;/code&gt; to a parameter when passing owned values as function arguments. This means the original owner will no longer have access to the value it once stored. Let's see what this looks like and how to resolve the issue.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello, world!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="cm"&gt;/* when we call `print_length()`, ownership moves to 
      the parameter `str` */&lt;/span&gt;
   &lt;span class="nf"&gt;print_length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="cm"&gt;/* the following line throws an error because 
      `s` no longer owns a value */&lt;/span&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; 
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// str takes ownership of arguments passed to this function&lt;/span&gt;
&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;print_length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Length of string: {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To avoid moving ownership to functions, we can write code that allows us to &lt;code&gt;borrow&lt;/code&gt; the value instead. To do this, our function parameters should take in a reference (&lt;code&gt;&amp;amp;&lt;/code&gt;) to a value rather than the value itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello, world!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nf"&gt;print_length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{s}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// prints "Hello, world!"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;print_length&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="c1"&gt;// prints "Length of string: 13"&lt;/span&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Length of string: {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can decide to move ownership into a function and later return and retake ownership. However, &lt;em&gt;it's often more common to &lt;code&gt;borrow&lt;/code&gt; values&lt;/em&gt;. &lt;/p&gt;




&lt;h2&gt;
  
  
  Mutable vs. Immutable values
&lt;/h2&gt;

&lt;p&gt;An &lt;code&gt;immutable&lt;/code&gt; value is a value that cannot change (read-only). By default, variables in Rust are immutable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="cm"&gt;/* this line will throw a compile 
               time error because `x` is immutable */&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{x}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A &lt;code&gt;mutable&lt;/code&gt; value is a value that can change. In Rust, we denote this with the &lt;code&gt;mut&lt;/code&gt; keyword.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// `x` is defined as a mutable&lt;/span&gt;
   &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{x}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// prints 20&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that you can pass &lt;code&gt;mutable references&lt;/code&gt; by combining what we learned about &lt;code&gt;borrowing&lt;/code&gt; with the &lt;code&gt;mut&lt;/code&gt; keyword. First, let's understand dereferencing, and then we will jump into a code example. &lt;code&gt;Dereferencing&lt;/code&gt; allows us to take a reference to a value and "follow it back" to its memory location, allowing us to modify it. This allows us to produce new results with existing data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// `y` holds a mutable reference to `x`&lt;/span&gt;
   &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// this line dereferences the value stored in `y`&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{y}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// prints 15&lt;/span&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{x}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// also prints 15&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since a mutable reference to &lt;code&gt;x&lt;/code&gt; passes to the variable &lt;code&gt;y&lt;/code&gt;, when &lt;code&gt;y&lt;/code&gt; mutates, &lt;code&gt;x&lt;/code&gt; reflects the changes.&lt;/p&gt;




&lt;h2&gt;
  
  
  Rules of Ownership
&lt;/h2&gt;

&lt;p&gt;Rust has a few rules for ownership that allow us to compile. By abiding by the following limitations, you'll be sure to have a great relationship with your compiler:&lt;/p&gt;

&lt;h3&gt;
  
  
  Each value can have, at most, a single owner
&lt;/h3&gt;

&lt;p&gt;Under the strictness of this rule, Rust can ensure precise control of memory throughout the life of your app. If an address can have many owners, imprecise management of that memory can lead to unwanted behavior.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hello"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// ownership of `s1` has moved to `s2`&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{s1}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="cm"&gt;/* this will result in an error, because 
                        `s1` has moved to `s2` */&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  When the owner goes out of scope, the value will drop
&lt;/h3&gt;

&lt;p&gt;This ensures that memory addresses free up when they are no longer used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;address&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="c1"&gt;// `temp` will drop when this inner scope ends&lt;/span&gt;
      &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;temp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello, world!"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
      &lt;span class="n"&gt;address&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;temp&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;

   &lt;span class="cm"&gt;/* Rust will throw a compile time error because we 
      are borrowing the value at `temp's` memory address: 
      "borrowed value does not live long enough" */&lt;/span&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{address}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  You cannot have more than one mutable reference to the same value in the same scope
&lt;/h3&gt;

&lt;p&gt;Allowing multiple mutable references creates ambiguity. How would we know what responsibilities we want each reference to have?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hi"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="c1"&gt;// we cannot have two mutable references to `s1`&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="cm"&gt;/* as soon as we try to make a mutation, Rust throws
      a compile time error */&lt;/span&gt;
   &lt;span class="n"&gt;s2&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;'!'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
   &lt;span class="n"&gt;s3&lt;/span&gt;&lt;span class="nf"&gt;.push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sc"&gt;'.'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{s1}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  You can have any number of immutable references as long as a mutable reference has not also been defined
&lt;/h3&gt;

&lt;p&gt;Rust will allow you to have as many &lt;code&gt;immutable&lt;/code&gt; references as you want. However, if you have declared a mutable reference, you cannot also have immutable references.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hi"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

   &lt;span class="c1"&gt;// Rust allows any number of immutable references&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;s4&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;s1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"{s2}, {s3}, {s4}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// prints "hi, hi, hi"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftif899mew5qoogsfex4u.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftif899mew5qoogsfex4u.jpg" alt="Looney toons that's all folks text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;See, wasn't too bad after all, right? Rust allows us to work with memory safely, and the compiler will ensure we are on the right path every step of the way! With an understanding of &lt;code&gt;ownership&lt;/code&gt;, &lt;code&gt;borrowing&lt;/code&gt;, &lt;code&gt;memory safety&lt;/code&gt;, &lt;code&gt;moves&lt;/code&gt;, &lt;code&gt;references&lt;/code&gt;, and more, you should be off writing 🔥&lt;em&gt;&lt;strong&gt;BLAZINGLY FAST&lt;/strong&gt;&lt;/em&gt;🔥 code in no time!&lt;/p&gt;

&lt;p&gt;Thanks for reading! I hope this blog post inspired your interest in the Rust language 🦀. For more information on &lt;code&gt;Ownership&lt;/code&gt; and &lt;code&gt;Borrowing&lt;/code&gt;, visit &lt;a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html" rel="noopener noreferrer"&gt;chapter 4 of The Rust Book&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Comments and feedback are greatly appreciated!&lt;/p&gt;

</description>
      <category>rust</category>
      <category>ownership</category>
      <category>borrowing</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
