<?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>DEV Community: Isuru Maldeniya</title>
    <description>The latest articles on DEV Community by Isuru Maldeniya (@isuru_maldeniya).</description>
    <link>https://dev.to/isuru_maldeniya</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%2F945354%2Ff110a8c2-ec90-49ba-b697-e0c54aca2726.jpeg</url>
      <title>DEV Community: Isuru Maldeniya</title>
      <link>https://dev.to/isuru_maldeniya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/isuru_maldeniya"/>
    <language>en</language>
    <item>
      <title>Exploring the difference between "any" and "unknown" in TypeScript</title>
      <dc:creator>Isuru Maldeniya</dc:creator>
      <pubDate>Mon, 21 Aug 2023 13:29:02 +0000</pubDate>
      <link>https://dev.to/isuru_maldeniya/exploring-the-difference-between-any-and-unknown-in-typescript-1p9k</link>
      <guid>https://dev.to/isuru_maldeniya/exploring-the-difference-between-any-and-unknown-in-typescript-1p9k</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;TypeScript, a widely adopted statically typed superset of JavaScript, elevates the level of type checking and overall code robustness within your projects. Amidst TypeScript's arsenal of type constructs, the "any" and "unknown" types emerge as versatile tools, offering pathways to navigate the complexities of uncertain or dynamically evolving data. Though these types might share a surface resemblance, delving deeper unravels their unique behaviors and distinct applications. This article ventures into the intricate realm of TypeScript's "any" and "unknown" types, shedding light on their disparities and furnishing invaluable guidance on the opportune application of each.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the basics
&lt;/h2&gt;

&lt;p&gt;TypeScript introduces static typing to JavaScript so that we can easily identify errors within our code in compiler time rather than in runtime. Types have proven ability to enhance code quality and understandability. &lt;br&gt;
However, there are instances where the nature of the data is either unknown or resistant to type constrictions. This is where the "any" and "unknown" types come into play. Both types can be thought of as escape hatches or safety valves that allow developers to circumvent strict type-checking when necessary.&lt;/p&gt;
&lt;h2&gt;
  
  
  The &lt;code&gt;any&lt;/code&gt; type
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;any&lt;/code&gt; type allows values of any type to be assigned to it, essentially disabling type checking for that particular value or variable. It provides maximum flexibility but sacrifices type safety. The compiler won't give any errors or warnings if you perform incompatible operations or access properties that may not exist.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let value: any;

value = 5; // No error, as any type allows any value
console.log(value.toFixed()); // No error, but may cause a runtime error if the value is not a number

value = "Hello";
console.log(value.length); // No error, but may cause a runtime error if the value does not have a length property

value = { foo: "bar" };
console.log(value.baz); // No error, but may cause a runtime error if the `baz` property doesn't exist

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  When to use &lt;code&gt;any&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JavaScript migration:&lt;/strong&gt; when transitioning the JavaScript code base to a TypeScript code base you can use &lt;code&gt;any&lt;/code&gt;, allowing you to maintain compatibility while gradually introducing stricter type later. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Third-Party Libraries:&lt;/strong&gt; When incorporating third-party JavaScript libraries lacking TypeScript type definitions, using the "any" type can be a practical solution. It allows you to interact with these libraries without extensive type annotations, albeit at the cost of some degree of type safety.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Heterogeneous Data:&lt;/strong&gt; Working with data structures that contain elements of different types, like arrays that hold various data objects, can be simplified using the &lt;code&gt;any&lt;/code&gt; type. This can be especially helpful when dealing with APIs that produce mixed data without a clear structure.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Drawback of using &lt;code&gt;any&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Type safety scarifies:&lt;/strong&gt; when using &lt;code&gt;any&lt;/code&gt;, it completely bypasses the powerful type system in TypeScript negating the benefit of static typing. This can lead to runtime errors and difficulties in identifying errors during development. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Refactoring Challenges:&lt;/strong&gt; As projects evolve, code needs to be refactored and extended. However, codebases heavily reliant on &lt;code&gt;any&lt;/code&gt; types can hinder this process, as type information is lost, making it harder to ensure code correctness during changes.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The &lt;code&gt;unknown&lt;/code&gt; type
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;unknown&lt;/code&gt; type is a type-safe counterpart of &lt;code&gt;any&lt;/code&gt;. It represents values that are of an unknown type at compile time. Unlike &lt;code&gt;any&lt;/code&gt;, you cannot perform arbitrary operations or access properties on values of type &lt;code&gt;unknown&lt;/code&gt; without proper type checking or assertions. It enforces developers to perform type checks before using the value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let value: unknown;

value = 5;
// console.log(value.toFixed()); // Error: Object is of type 'unknown'

if (typeof value === "number") {
  console.log(value.toFixed()); // No error, type check ensures it's a number
}

value = "Hello";
// console.log(value.length); // Error: Object is of type 'unknown'

if (typeof value === "string") {
  console.log(value.length); // No error, type check ensures it's a string
}

value = { foo: "bar" };
// console.log(value.baz); // Error: Object is of type 'unknown'

if (typeof value === "object" &amp;amp;&amp;amp; value !== null) {
  console.log(value.baz); // No error, type check ensures it's an object and `baz` may not exist
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  When to use &lt;code&gt;unknown&lt;/code&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Accessing external data sources:&lt;/strong&gt; when interacting with external APIs or data sources the nature of incoming data may be uncertain. In these scenarios, we can use &lt;code&gt;unknown&lt;/code&gt; to validate incoming data before proceeding to reduce runtime errors. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Type checking enforcement:&lt;/strong&gt; The &lt;code&gt;unknown&lt;/code&gt; is an enforcer of robust type checking. It ensures that before proceeding you always do a type validation which diminishes the risk of unexpected behavior. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Type safety and refactoring
&lt;/h2&gt;

&lt;p&gt;The difference between &lt;code&gt;any&lt;/code&gt; and &lt;code&gt;unknown&lt;/code&gt; becomes more evident when considering code evolution and maintenance. Consistency using &lt;code&gt;any&lt;/code&gt; can lead to a brittle codebase. During refactoring due to loss of type information when using &lt;code&gt;any&lt;/code&gt; can lead to unexpected errors emerging, making the process of code modification extremally hard.&lt;br&gt;
On the other hand, the &lt;code&gt;unknown&lt;/code&gt; allows us to write refactor-friendly code. Its requirement for explicit type validation forces developers to consider type implications as they evolve the codebase. As a result, when you refactor code using "unknown," TypeScript guides you through the changes needed to maintain type safety, ensuring that your modifications align with the expected data types.&lt;/p&gt;

&lt;h2&gt;
  
  
  Best practices
&lt;/h2&gt;

&lt;p&gt;To sum up the usage between &lt;code&gt;any&lt;/code&gt; and &lt;code&gt;unknown&lt;/code&gt;,&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;any&lt;/code&gt; if type information is inaccessible or incompatible, and ensure that clear strategies are in place to mitigate its downsides.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use &lt;code&gt;unknown&lt;/code&gt; when using external data sources, enforcing type checking, and enhancing code stability during refactoring. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In conclusion by leveraging the capabilities of "unknown" and using "any" judiciously, developers can strike a balance between flexibility and type safety, leading to more robust and adaptable TypeScript codebases.&lt;/p&gt;

&lt;h2&gt;
  
  
  Additional resources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html"&gt;Everyday Types&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;😀😄 Hope this article helped you to understand more about difference between &lt;code&gt;any&lt;/code&gt; vs &lt;code&gt;unknown&lt;/code&gt;. Happy Coding! 👌👌🧑‍💻&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>programming</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
