<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nacho Gavilanes on Medium]]></title>
        <description><![CDATA[Stories by Nacho Gavilanes on Medium]]></description>
        <link>https://medium.com/@gavilanesignacio?source=rss-05d4b8fe528a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-1WOuIakPPAuMzMUJhUFiQ.png</url>
            <title>Stories by Nacho Gavilanes on Medium</title>
            <link>https://medium.com/@gavilanesignacio?source=rss-05d4b8fe528a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:45:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gavilanesignacio/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TypeScript Fundamentals]]></title>
            <link>https://medium.com/neocoast/typescript-fundamentals-86dd5085b7eb?source=rss-05d4b8fe528a------2</link>
            <guid isPermaLink="false">https://medium.com/p/86dd5085b7eb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Nacho Gavilanes]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 13:31:22 GMT</pubDate>
            <atom:updated>2025-07-09T13:31:22.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NRDGJRVPV1bT-jTyxhEZw.png" /></figure><h4>BEGINNER-FRIENDLY</h4><h4>Diving Deeper (Part 2/2)</h4><p>Whether you’re continuing from <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>Part I</strong></a><strong> </strong>or jumping in fresh, you’re in the right place.</p><p>In the first part, we covered TypeScript’s origins, how the compiler works, and foundational type system concepts like aliases and unions. While this post works on its own, the first part sets the stage nicely and might be worth a quick detour if you’re curious.</p><p>Now that we’ve set the foundation, it’s time to take things up a notch.</p><p>In this second part, we’ll dive into more advanced features that make TypeScript truly powerful. We’ll explore <strong>utility types</strong> like Pick and Omit, work with advanced <strong>operators</strong> such as typeof and as, and learn how to <strong>extend type definitions</strong> in a clean and scalable way. We’ll also talk about the unknown type, get hands-on with <strong>generics</strong>, and see how TypeScript integrates smoothly with <strong>React</strong>.</p><p>By the end of this post, you’ll be equipped to write more expressive, reusable, and robust TypeScript code.</p><p>Let’s dive in!</p><h3>Utility types</h3><p>TypeScript comes with several built-in <a href="https://www.typescriptlang.org/docs/handbook/utility-types.html"><strong>utility types</strong></a> that help you work with types more efficiently. These utility types are defined using something called <strong>generics</strong>. We’ll talk more about generics towards the end of this blog, but for now, all you need to know is that they allow a type definition to work with many different kinds of values instead of just one specific type.</p><p>Utility types make use of this flexibility to perform common type-level operations in a reusable way. While we won’t cover every utility type here, we’ll explore a few particularly useful ones.</p><h4>Readonly&lt;Type&gt;</h4><p>This utility type is self explanatory, it allows us to construct a type where all properties are <strong>non-reassignable</strong>. Here is a quick example:</p><pre>type Todo = {<br>  title: string;<br>};<br> <br>const todo: Readonly&lt;Todo&gt; = {<br>  title: &quot;Delete inactive users&quot;,<br>};<br> <br>todo.title = &quot;Hello&quot;; // ❌ Error: Can&#39;t re-assign &#39;title&#39;, it&#39;s read-only</pre><p>With Readonly, trying to reassign the title property will result in an error. This is useful when you want to prevent changes to certain objects or properties after they have been initialized. One practical way to use Readonly is to mark function parameters as immutable, ensuring the function won’t modify the array passed in. Consider this snippet:</p><pre>function printLanguages(langs: Readonly&lt;string[]&gt;) {<br>  // langs.push(&#39;de&#39;); // ❌ No property &#39;push&#39; on type &#39;readonly string[]&#39;<br>  langs.forEach(lang =&gt; console.log(lang));<br>}<br><br>const myLangs = [&#39;en&#39;, &#39;es&#39;, &#39;fr&#39;];<br>printLanguages(myLangs);</pre><p>In this example, the commented-out line tries to add a language to the langs array, but doing so causes an error because langs is readonly inside the function. This prevents accidental mutation while still allowing callers to pass regular mutable arrays.</p><h4>Record&lt;Keys, Type&gt;</h4><p>The Record utility type allows us to specify both the keys and the values of an object. You might be thinking, <em>wait a minute, didn’t we already learn how to type an object in </em><a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong><em>Part I</em></strong></a><em>?</em> And you’d be right:</p><pre>let sample: { a: number; b: boolean; c: string; } = {<br>  a: 2,<br>  b: true,<br>  c: &quot;this a string&quot;,<br>};</pre><p>This works just fine for simple cases. But notice that while the values are typed, the keys (a, b, c) are just string literals (they aren&#39;t enforced by a type). That’s where Record comes in handy, it lets you explicitly define a fixed set of keys and the type of their values.</p><pre>type DogName = &quot;loki&quot; | &quot;trufa&quot; | &quot;otto&quot;;<br><br>interface DogInfo {<br>  age: number;<br>  breed: string;<br>}<br><br>const dogs: Record&lt;DogName, DogInfo&gt; = {<br>  loki: { age: 3, breed: &quot;Labrador&quot; },<br>  trufa: { age: 5, breed: &quot;Chihuahua&quot; },<br>  otto: { age: 2, breed: &quot;Border Collie&quot; },<br>};</pre><p>In this example, we not only define the value objects (age and breed) for the dogs, but we also define the type for the keys using the DogName <strong>union type</strong>, ensuring dogs can only be named loki, trufa, or otto.</p><h4>Pick&lt;Type, Keys&gt; and Omit&lt;Type, Keys&gt;</h4><p>We’ll cover these two utility types together because they are essentially opposites. Pick and Omit let you select and exclude properties, respectively, from an existing type to create a new one. Here’s an example to illustrate how they work:</p><pre>type Sandwich = {<br>  bread: string;<br>  meat: string;<br>  cheese: string;<br>  lettuce: string;<br>  tomato: string;<br>  mayonnaise: string;<br>};<br><br>type BoringSandwich = Pick&lt;Sandwich, &quot;bread&quot; | &quot;cheese&quot;&gt;;<br><br>type VegetarianSandwich = Omit&lt;Sandwich, &quot;meat&quot;&gt;;</pre><p>For the BoringSandwich type, we only picked the bread and cheese properties, whereas the VegetarianSandwich type has all of Sandwich properties except for the meat property.</p><p>While utility types make it easy to manipulate existing type structures, there are cases where they’re not the most efficient tool. For instance, say we have a base User type with a ton of properties such as, id, firstName, lastName, email, username, profilePicture, and many more. If we want to define an AdminUser that shares all the same properties but also includes admin-specific permissions, using Pick or Omit to recreate the entire User shape would be tedious and repetitive. Fortunately, TypeScript offers more efficient ways to build on top of existing types, allowing us to extend definitions rather than reconstruct them piece by piece.</p><h3>Extending a definition</h3><p>Now that we’ve seen how Pick and Omit can selectively shape types, you might be wondering how to expand a type instead (creating a superset that inherits the original structure and adds new capabilities). There are two primary ways to do this in TypeScript, depending on whether you&#39;re working with interfaces or type aliases.</p><p>For a type alias definition, we use the <strong>intersect operator</strong> (&amp;):</p><pre>type Computer = {<br>  brand: string;<br>  model: string;<br>  processor: string;<br>  memory: number;<br>  storage: number;<br>  powerOn(): void;<br>};<br><br>type Laptop = Computer &amp; {<br>  batteryLife: number;<br>  weight: number;<br>  isTouchscreen: boolean;<br>};</pre><p>And for interfaces we use the extends keyword:</p><pre>interface Computer {<br>  brand: string;<br>  model: string;<br>  processor: string;<br>  memory: number;<br>  storage: number;<br>  powerOn(): void;<br>}<br><br>interface Laptop extends Computer {<br>  batteryLife: number;<br>  weight: number;<br>  isTouchscreen: boolean;<br>}</pre><p>This approach allows us to effortlessly build on top of existing types with minimal effort.</p><h3>Typescript operators and modifiers</h3><p>TypeScript gives us a handful of powerful modifiers and type operators. These are tools you can use to manipulate, extract, or assert types. They help make your types more precise. We’ve already described the optional (?) modifier and union (|) operator in <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>Part I</strong></a>, and just recently went over the intersection (&amp;) operator. Now, let’s take a look at a few more that are equally important.</p><h4>readonly modifier</h4><p>The readonly modifier makes individual properties <strong>immutable</strong>. It works similarly to the Readonly utility type we just covered, but with a key difference: while Readonly applies to an entire object or array, the readonly modifier gives you more <strong>granular control</strong>, allowing you to mark <strong>specific properties</strong> as read-only.</p><p>Take a User type, for instance, where fields like id or createdAt should never be modified after being set. Here is an example using the readonly modifier:</p><pre>type User = {<br>  readonly id: number;<br>  name: string;<br>};<br><br>const user: User = { id: 1, name: &#39;Alex&#39; };<br><br>user.id = 2; // ❌ Cannot assign to &#39;id&#39; because it is a read-only property</pre><h4>as operator</h4><p>In JavaScript, as is valid only in import/export syntax. In TypeScript, it&#39;s used for <strong>type assertions</strong>.</p><pre>const input = document.querySelector(&#39;input&#39;) as HTMLInputElement;</pre><p>Here we are telling TypeScript: <em>I know exactly what input is; you should not infer it. I know without a doubt input is an </em><em>HTMLInputElement.</em> TypeScript normally infers the return type as Element | null, but you&#39;re asserting that it’s an HTMLInputElement, so you can safely access .value.</p><p>There is also a construct, as const, that not only <strong>makes values immutable</strong> but also <strong>preserves their exact literal types</strong>. This is known as a <a href="https://arc.net/l/quote/kqkwrnys"><strong>const assertion</strong></a>:</p><pre>const method = &#39;POST&#39; as const;</pre><p>Here, method is not of type string; it is the exact string literal type &#39;POST&#39;. This means you can&#39;t reassign it, and TypeScript will treat it as the literal type &#39;POST&#39;, which is more specific than a general string.</p><p><strong>How is </strong><strong>as const different from </strong><strong>readonly and </strong><strong>Readonly?</strong></p><ul><li>The readonly modifier is used for individual properties or variable declarations.</li><li>The Readonly utility type makes all properties of an object type read-only, but only at the top level (<strong>shallow immutability</strong>).</li></ul><p>By contrast, as const does two things:</p><ul><li>Makes the entire object <strong>deeply immutable</strong>.</li><li>Narrows the type to <strong>exact literals</strong> (e.g., &#39;POST&#39; instead of string).</li></ul><p>A practical example of as const usage is with the <a href="https://github.com/i18next/i18next">i18n</a> library, which handles internationalization by using translation files. These files typically store structured text content for different languages. The i18n docs recommend using as const to get both deep immutability and precise literal types, which improves safety and auto-completion.</p><pre>const translations = {<br>  home: {<br>    title: &#39;Welcome!&#39;,<br>    description: &#39;Start your journey here.&#39;,<br>  },<br>  contact: {<br>    form: {<br>      email: &#39;Email address&#39;,<br>      feedback: &#39;Leave your feedback here&#39;,<br>      button: &#39;Send&#39;,<br>    },<br>  // other keys...<br>  }<br>} as const;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-rcDADJZ_6bhqphv8996w.gif" /><figcaption>TypeScript’s <strong>as const</strong> makes every nested value literal and <strong>readonly</strong>.</figcaption></figure><p>If we had instead used Readonly&lt;typeof translations&gt;, we would only get shallow immutability. That means the top-level keys, home and contact, would be read-only, but their nested properties would still be:</p><ul><li>Mutable (not readonly)</li><li>Typed as general string values rather than their exact string literals</li></ul><p>We can take this a step further by combining as const with the satisfies operator. While as const gives us deep immutability and exact literal types, adding satisfies ensures the object also conforms exactly to a predefined structure.</p><p>A practical application, and continuing from our last code example, is managing multiple translation files. This helps prevent issues like missing keys or accidental fallbacks, such as an English string appearing on a Spanish site because a key was left out.</p><p>Typically, you’d define a type schema like this:</p><pre>type TranslationSchema = {<br>  home: {<br>    title: string;<br>    description: string;<br>  };<br>  contact: {<br>    form: {<br>      email: string;<br>      feedback: string;<br>      button: string;<br>    };<br>  // other keys...<br>  }<br>};</pre><p>Then, each translation file (english.ts, spanish.ts, etc) would look like this:</p><pre>const translations = {<br>  home: {<br>    title: &#39;Welcome!&#39;,<br>    passiveAggressiveTooltip: &#39;Sure, just scroll past all our hard work.&#39;,<br>    description: &#39;Start your journey here.&#39;,<br>  },<br>  contact: {<br>    form: {<br>      email: &#39;Email address&#39;,<br>      feedback: &#39;Leave your feedback here&#39;,<br>      button: &#39;Send&#39;,<br>    },<br>  // other keys...<br>  }<br>} as const satisfies TranslationSchema;</pre><p>This way if we forgot to add a key or added a key that is not specified in TranslationSchema, we would see an error like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zprQpD_f6JtgjyURWTXNaw.gif" /><figcaption>Adding the <strong>passiveAggressiveSubtitle</strong> property to the translation results in an error since it’s not defined in<strong> TranslationSchema</strong>.</figcaption></figure><h4>typeof operator</h4><p>You’ve probably used typeof in JavaScript before. It’s a runtime operator that returns a string describing the type of a value:</p><pre>typeof &#39;hello&#39;; // &#39;string&#39;<br>typeof 42; // &#39;number&#39;</pre><p>In TypeScript, typeof has an additional use: it can be used at the type level to extract the type of a variable or constant:</p><pre>const user = {<br>  id: 1,<br>  name: &#39;Robert&#39;<br>};<br><br>type User = typeof user;<br>// Equivalent to: { id: number; name: string }</pre><p>This is super useful when you want to reuse the type of an existing value (especially constants or config objects) without repeating yourself.</p><h4>keyof operator</h4><p>keyof is a <strong>TypeScript-only</strong> operator that returns a <strong>union of the keys</strong> of a given type:</p><pre>type User = {<br>  id: number;<br>  name: string;<br>};<br><br>type UserKeys = keyof User; // &#39;id&#39; | &#39;name&#39;</pre><p>This is particularly useful for creating <strong>generic utilities</strong>, or when you want to restrict inputs to valid keys of an object:</p><pre>function getValue&lt;T, K extends keyof T&gt;(obj: T, key: K) {<br>  return obj[key];<br>}<br><br>const user = { id: 1, name: &#39;Bill&#39; };<br><br>getValue(user, &#39;name&#39;); // ✅ Allowed<br>getValue(user, &#39;age&#39;); // ❌ Error: &#39;age&#39; is not a key of &#39;user&#39;</pre><p>Don’t worry if this syntax seems unfamiliar; we’ll cover generics later, and it will feel more natural then.</p><p>Finally, you can also combine keyof with typeof to extract the keys from a <strong>real object</strong>:</p><pre>const settings = {<br>  theme: &#39;dark&#39;,<br>  fontSize: 14<br>};<br><br>type SettingKeys = keyof typeof settings; // &#39;theme&#39; | &#39;fontSize&#39;</pre><p>All these tools for type manipulation are great, but sometimes you’re dealing with values that you can’t confidently type at all. That’s where the unknown type comes in. We first introduced unknown in <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>Part I</strong></a> as a safer alternative to any. In the next section, we’ll explore it further and learn how to take full advantage of its capabilities.</p><h3>The unknown keyword</h3><p>Back in <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>Part I</strong></a>, when we introduced inline async function type definitions, we used an example like this:</p><pre>async function getFavoriteNumber(): Promise&lt;number&gt; {<br>  return 26;<br>}</pre><p>Here, we explicitly added Promise&lt;number&gt; as the return type. But in simple cases like this, TypeScript can actually infer it automatically. In this case, async tells TypeScript the function returns a Promise, and since 26 is a number, the full return type is inferred as Promise&lt;number&gt;.</p><p>However, for more complex return values, it’s good practice to <strong>explicitly define the type</strong>, especially when the returned value is an object with a known shape:</p><pre>interface User {<br>  readonly id: string;<br>  name: string;<br>  email?: string;<br>  profilePicture?: string;<br>  birthDate?: string;<br>}<br><br>async function getUser(): Promise&lt;User&gt; {<br>  const res = await fetch(&#39;/api/user&#39;);<br>  const data = await res.json();<br>  return data;<br>}</pre><p>Here, Promise&lt;User&gt; gives you confidence that the function will return something that matches the User interface.</p><p>This approach works well for internal APIs you control. But what happens when you’re working with <strong>third-party APIs</strong>, where you <em>think</em> you know what the data looks like… but you’re not completely sure? That’s where the unknown type becomes useful. By returning unknown, TypeScript <strong>does not let you use the value directly until you validate or narrow down its type</strong>:</p><pre>function processData(data: unknown) {<br>  console.log(data.name); // ❌ Error: Object is of type &#39;unknown&#39;<br>}<br><br>function processData(data: unknown) {<br>  if (typeof data === &quot;string&quot;) {<br>    console.log(data.toUpperCase()); // ✅ Safe<br>  } else {<br>    console.log(&quot;Not a string&quot;);<br>  }<br>}</pre><h4>unknown vs any</h4><p>So, <em>why not just use </em><em>any</em>? Because any lets you do <em>anything</em>, without any type checking at all, which can lead to runtime errors. In contrast, unknown provides some flexibility while still enforcing that you narrow down the type before using it. Here is a quick comparison:</p><pre>function processData(data: unknown) {<br>  console.log(data.foo); // ❌ Error: needs type checking<br>}<br><br>function processData(data: any) {<br>  console.log(data.foo.bar.baz); // ✅ No error, but no safety<br>}</pre><p>In the example above, trying to access properties on an unknown value without first checking its type results in a TypeScript error. Meanwhile, using any bypasses all checks, allowing potentially unsafe code that may crash at runtime.</p><p>Using unknown forces you to be explicit about how you handle the data, making your code more robust and less prone to runtime errors.</p><p>One last important thing about the unknown type is that it works really well with schema validators (tools that check the shape of your data <strong>at runtime</strong>). While TypeScript checks types at compile time (before your code runs), schema validators like <a href="https://github.com/colinhacks/zod">Zod</a> and <a href="https://github.com/jquense/yup">Yup</a> validate data while your app is running.</p><p>These validators let you define exactly what shape you expect. For instance, a to-do object with an id, title, and completed field, and then safely check that the incoming data matches that shape. Here&#39;s how that looks in practice:</p><pre>import { z } from &quot;zod&quot;;<br><br>const todoSchema = z.object({<br>  id: z.number(),<br>  title: z.string(),<br>  completed: z.boolean(),<br>});<br><br>useEffect(() =&gt; {<br>  fetch(&quot;https://jsonplaceholder.typicode.com/todos/1&quot;)<br>    .then((res) =&gt; res.json())<br>    .then((data: unknown) =&gt; {<br>      const todo = todoSchema.parse(data); // throws if shape doesn&#39;t match<br>      console.log(todo.title); // safe to use!<br>    });<br>}, []);</pre><p>Once your data passes validation, TypeScript knows it conforms to the expected type.</p><h3>React and TypeScript</h3><p>Nowadays, most <a href="https://react.dev/learn/start-a-new-react-project#production-grade-react-frameworks">React frameworks</a> include TypeScript support out of the box. <a href="https://nextjs.org/">Next.js</a>, for example, no longer asks if you want to add it, it just sets everything up automatically (although you can disable it if you prefer not to use TypeScript).</p><p>So while there’s nothing particularly tricky about getting started, there are some patterns and best practices worth knowing to use React and TypeScript effectively. Let’s walk through them.</p><blockquote>If you’re already comfortable with React-specific TypeScript patterns (like typing props, refs, or component state), feel free to jump ahead to the <strong>Generics</strong> section.</blockquote><h4>Components</h4><p>Back in the day, you might have seen components typed like this:</p><pre>const MyComponent: React.FC = () =&gt; {<br>  return &lt;div&gt;Hello&lt;/div&gt;;<br>};</pre><p>That React.FC (short for React.FunctionComponent) was once the standard way to type functional components in TypeScript. It provides some conveniences out of the box:</p><ul><li>Automatically types children as a prop</li><li>Ensures the return type is valid JSX</li><li>Gives a consistent function signature for your components</li></ul><p>These days though, using React.FC is no longer considered best practice. While it&#39;s still included in @types/react, it introduces implicit behavior (like always including children even when your component doesn’t use them).</p><p>This can make your types less precise and your components harder to reason about. Instead, the modern recommendation is to define props explicitly using an interface or type alias. This approach avoids surprises from the extra types React.FC injects behind the scenes. We’ll put this into practice in the next section.</p><h4>Props</h4><p>When working with a React component, the key TypeScript-specific feature is typing your component’s props. Since props are just an object, the syntax mirrors what we saw in the basics of TypeScript in <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>Part I</strong></a>.</p><pre>function MyButton({ onClick }: { onClick: () =&gt; void }) {<br>  return (<br>    &lt;button onClick={onClick}&gt;<br>     Click me!<br>   &lt;/button&gt;<br>  );<br>}<br><br>export default function MyApp() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to my app&lt;/h1&gt;<br>      &lt;MyButton onClick={() =&gt; console.log(&#39;clicked!&#39;)} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This inline approach is the simplest way to provide types for a component. However, as the number of props grows, this method can become hard to read and maintain. Let’s extract the prop types using a type alias and add a new disabled prop:</p><pre>type MyButtonProps = {<br>  onClick: () =&gt; void;<br>  disabled: boolean;<br>};<br><br>function MyButton({ onClick, disabled }: MyButtonProps) {<br>  return (<br>    &lt;button<br>     onClick={onClick}<br>     disabled={disabled}<br>    &gt;<br>     Click me!<br>   &lt;/button&gt;<br>  );<br>}</pre><p>Our component wraps the native HTML &lt;button&gt; element. As you can imagine, a &lt;button&gt; accepts a wide range of props. But, <em>should we type them all manually?</em> What if we wanted to accept a style prop too? <em>Would we have type all possible css properties ourselves?</em> That would be a maintenance nightmare. HTML buttons have dozens of valid attributes, and we’d need to keep our type definition updated with any changes to the HTML spec.</p><p>Fortunately, React provides us with a built-in utility type for this: ButtonHTMLAttributes. This type includes all properties a &lt;button&gt; can receive (HTML attributes like onClick, disabled, style as well as React-specific props such as key).</p><p>So, <em>where does this utility come from?</em> When you install @types/react, TypeScript reads from type definitions stored in node_modules/@types/react. These types are part of a community-maintained repo called <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a>, which we covered in <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>Part I</strong></a>.</p><p>That said, let’s update our prop type alias using the React utility type introduced above:</p><pre>import { ComponentPropsWithoutRef } from &#39;react&#39;;<br><br>type MyButtonProps = ComponentPropsWithoutRef&lt;&#39;button&#39;&gt;;<br><br>function MyButton({ onClick, disabled }: MyButtonProps) {<br>  return (<br>    &lt;button<br>      onClick={onClick}<br>      disabled={disabled}<br>    &gt;<br>      Click me!<br>    &lt;/button&gt;<br>  );<br>}</pre><p>ComponentPropsWithoutRef&lt;’button’&gt; provides all the native &lt;button&gt; props without requiring you to manually type each one.</p><p>Using ComponentPropsWithoutRef is generally preferred over older alternatives like ComponentProps, which is too broad, or ButtonHTMLAttributes&lt;HTMLButtonElement&gt;, which excludes React-specific props such as ref and key. If you do need ref, you can use ComponentPropsWithRef&lt;’button’&gt; instead.</p><p>Now, if we want to pass other properties that a button normally accepts, such as autoFocus, we won’t get an error. Furthermore, if we need to pass a property that a button does not natively accept, like variant, we’ll need to extend MyButtonProps to include it in the type alias, like so:</p><pre>import { ComponentPropsWithoutRef } from &#39;react&#39;;<br><br>type MyButtonProps = ComponentPropsWithoutRef&lt;&#39;button&#39;&gt; &amp; {<br>  variant: &#39;primary&#39; | &#39;secondary&#39; = &#39;primary&#39;;<br>};<br><br>function MyButton({ onClick, disabled }: MyButtonProps) {<br>  return (<br>    &lt;button<br>      onClick={onClick}<br>      disabled={disabled}<br>    &gt;<br>     Click me!<br>   &lt;/button&gt;<br>  );<br>}</pre><p>Now variant is a valid optional prop, defined as a union of two strings with ‘primary’ being the default.</p><h4>Children</h4><p>Now let’s say we have a Modal component whose job is to confirm the deletion of an item from your cart:</p><pre>type Button = {<br>  label: string;<br>  action: () =&gt; void;<br>};<br><br>type DeletionConfirmationModalProps = {<br>  title: string;<br>  isOpen: boolean;<br>  closeModal: () =&gt; void;<br>  primaryButton: Button;<br>  secondaryButton: Button;<br>}<br><br>export default function DeletionConfirmationModal ({<br>  title,<br>  isOpen,<br>  closeModal,<br>  primaryButton,<br>  secondaryButton,<br>}: DeletionConfirmationModalProps) {<br>  return (<br>    &lt;dialog open={isOpen} onClose={closeModal}&gt;<br>      &lt;h3&gt;{title}&lt;/h3&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={primaryButton.action}&gt;<br>          {primaryButton.label}<br>        &lt;/button&gt;<br>        &lt;button onClick={secondaryButton.action}&gt;<br>          {secondaryButton.label}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/dialog&gt;<br>  );<br>}</pre><p>This version works fine, but it isn’t very flexible. For example, <em>what if you want to include custom content like a message, an image, or other UI elements inside the modal?</em> Right now, you’re stuck with just the title and two buttons.</p><p>To make this component more modular and reusable, we can take advantage of the children prop. To do that, we&#39;ll need to use another utility type from React:</p><pre>import { ReactNode } from &#39;react&#39;;<br><br>type Button = {<br>  label: string;<br>  action: () =&gt; void;<br>};<br><br>type DeletionConfirmationModalProps = {<br>  title: string;<br>  isOpen: boolean;<br>  closeModal: () =&gt; void;<br>  primaryButton: Button;<br>  secondaryButton: Button;<br>  children: ReactNode;<br>};<br><br>export default function DeletionConfirmationModal ({<br>  title,<br>  isOpen,<br>  closeModal,<br>  primaryButton,<br>  secondaryButton,<br>  children,<br>}: DeletionConfirmationModalProps) {<br>  return (<br>    &lt;dialog open={isOpen} onClose={closeModal}&gt;<br>      &lt;h3&gt;{title}&lt;/h3&gt;<br>      &lt;div&gt;<br>        {children}<br>        &lt;button onClick={primaryButton.action}&gt;<br>          {primaryButton.label}<br>        &lt;/button&gt;<br>        &lt;button onClick={secondaryButton.action}&gt;<br>          {secondaryButton.label}<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/dialog&gt;<br>  );<br>}</pre><p>Here, we used ReactNode to type the children prop, allowing the component to accept a wide range of valid React content. ReactNode is a flexible type that covers everything from strings and numbers to JSX elements, fragments, arrays, and more. If you want to be stricter and only allow JSX elements, you can use JSX.Element instead.</p><h4>Hooks</h4><p>The type definitions from @types/react include types for the built-in hooks, so you can use them in your components without any additional setup. These types are smart enough to infer based on how you use the hook, so in many cases you won’t need to annotate types manually.</p><p><strong>useState</strong></p><p>TypeScript inference uses the value we utilize to initialize the useState value. In simple cases where we have something like:</p><pre>const [isLoading, setIsLoading] = useState(false);</pre><p>Here, we don’t need to specify a type, because TypeScript can easily infer that isLoading is a boolean.</p><p>However, there are cases where you should explicitly annotate the type. One common case is when the state is initially null but will later hold an object, such as when fetching data:</p><pre>type User = {<br>  name: string;<br>  age: number;<br>};<br><br>export default function Button() {<br>  const [user, setUser] = useState&lt;User | null&gt;(null);<br><br>  // etc<br>}</pre><p>Or in cases where the value should be restricted, like this:</p><pre>type Status = &quot;idle&quot; | &quot;loading&quot; | &quot;success&quot; | &quot;error&quot;;<br><br>const [status, setStatus] = useState&lt;Status&gt;(&quot;idle&quot;);</pre><p>In both cases, we’re giving TypeScript more information than it could safely infer on its own.</p><p>The last thing I’d like to mention is that when passing a setter to a child component, the type should look something like this:</p><pre>type MyComponentProps = {<br>  setCount: React.Dispatch&lt;React.SetStateAction&lt;number&gt;&gt;;<br>};</pre><p>This might look intimidating, but you don&#39;t need to memorize it. Just hover over the setter, and TypeScript will give you the exact type you need as seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7YFfXMFb9myNOGNNL8x1w.gif" /><figcaption>Hovering over the <strong>useState</strong> instance definition shows us the actual type.</figcaption></figure><p>It’s worth noting that if you’re using React 17 or newer with automatic JSX runtime, you may not be explicitly importing React anymore. In that case, TypeScript won’t recognize React.Dispatch or React.SetStateAction unless you import them. So, just do:</p><pre>import { Dispatch, SetStateAction } from &#39;react&#39;;</pre><p><strong>useRef</strong></p><p>In TypeScript, when you initialize a ref with null, React&#39;s type definitions infer the type of the ref&#39;s .current property as T | null, where T is the type of the DOM element. This means that .current can be either the DOM element or null if the element hasn&#39;t been rendered yet.</p><p>For example, initializing a ref for a button element:</p><pre>const buttonRef = useRef&lt;HTMLButtonElement&gt;(null);</pre><p>In this case, buttonRef.current is inferred as HTMLButtonElement | null.</p><p>When you create a ref to store <strong>non-DOM values</strong> (like a timer ID), you should include | null in the type if you initialize the ref with null. This correctly reflects that .current may be null before you assign a valid value.</p><pre>const timerRef = useRef&lt;number | null&gt;(null);</pre><h4>DOM events</h4><p>Even though events aren’t specific to React, you work with them extensively in React projects. Let’s use an onClick event as an example:</p><pre>return &lt;button onClick={(e) =&gt; console.log(e, &#39;click!&#39;)}&gt;Click me!&lt;/button&gt;</pre><p>we could hover over the e, and see the corresponding type definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfYggNNxgVRJCwDBcPIlpA.gif" /><figcaption>Here we can see how when defining the event handler <strong>inline</strong>, TypeScript <strong>infers</strong> its type.</figcaption></figure><p>But if we were to define the function elsewhere and then pass it on to the onClick handler like so:</p><pre>const handleOnClick = (e) =&gt; console.log(e, &#39;clicked!&#39;);<br><br>return &lt;button onClick={handleOnClick}&gt;Click me!&lt;/button&gt;</pre><p>We would get the red squiggly lines telling us that e has a type of any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLl75trKheQaxTSsfDW5aQ.gif" /><figcaption>Here we can see how defining the <strong>onClick</strong> event handler <strong>outside</strong> the button results in TypeScript <strong>not being able to infer the type</strong> of e.</figcaption></figure><p>This happens because inference only works inline, and when you extract the function, there’s no context to pick up the type.</p><p>One thing we can do in cases like this is to define the function inline, hover over the inferred types, copy them and then just paste them in the function definition.</p><h3>Generics</h3><p>You can think of generics as <strong>placeholders for types</strong>, allowing you to delay deciding the exact type a function or component will work with. Generics are utilized to build reusable and type-safe components.</p><p>Let’s go over an example, <em>how would you type the argument of a function that simply returns whatever value type you provide?</em></p><pre>function identity(value: any) {<br>  return value;<br>}</pre><p>Using any means we lose type safety, because TypeScript can’t infer whether value will be a number, string, object, or anything else. That’s precisely the problem <strong>generics</strong> exist to solve:</p><pre>function identity&lt;T&gt;(value: T): T {<br>  return value;<br>}</pre><p>Now, whatever type we pass in, the function returns <strong>that exact same type</strong>. So if we pass in a number, it returns a number. If we pass a string, it returns a string:</p><pre>identity(5); // T is number<br>identity(&quot;hello&quot;); // T is string</pre><blockquote><strong>A quick note on generics in .tsx files<br></strong>When using generics in arrow functions, add a comma after the type:</blockquote><blockquote>const convertToArray = &lt;T,&gt;(value:T): T[] =&gt; [value];<br><br>Without the comma, &lt;T&gt; may be misinterpreted as a JSX tag. The comma ensures TypeScript treats it as a generic, not JSX.</blockquote><h4>Generics in React components</h4><p>Suppose we want to create a reusable List component that takes an array of items and renders each one:</p><pre>type ListProps&lt;T&gt; = {<br>  items: T[];<br>  renderItem: (item: T) =&gt; JSX.Element;<br>};<br><br>function List&lt;T&gt;({ items, renderItem }: ListProps&lt;T&gt;) {<br>  return &lt;ul&gt;{items.map(renderItem)}&lt;/ul&gt;;<br>}</pre><p>Now we can use it with <strong>any kind of list</strong>:</p><pre>&lt;List<br>  items={[&quot;Apple&quot;, &quot;Banana&quot;, &quot;Orange&quot;]}<br>  renderItem={(fruit) =&gt; &lt;li key={fruit}&gt;{fruit}&lt;/li&gt;}<br>/&gt;<br><br>&lt;List<br>  items={[{ id: 1 }, { id: 2 }]}<br>  renderItem={(item) =&gt; &lt;li key={item.id}&gt;Item {item.id}&lt;/li&gt;}<br>/&gt;</pre><p>TypeScript keeps track of the type inside items and makes sure the renderItem function matches.</p><h4>Constraining generics</h4><p>Sometimes you want to limit what T can be. Let’s say we want a function that only works with objects that have an id property:</p><pre>function getId&lt;T extends { id: number }&gt;(item: T): number {<br>  return item.id;<br>}</pre><p>This way, if you try to call getId on something that doesn’t have an id, you’ll get a TypeScript error.</p><pre>getId({ id: 42 }); // ✅<br>getId({ name: &quot;John&quot; }); // ❌ Property &#39;id&#39; is missing</pre><h3>Conclusion</h3><p>TypeScript adds a powerful type system to JavaScript, helping developers catch errors early, write more predictable code, and build scalable applications with confidence.</p><p>In this guide, you’ve not only learned the fundamentals of TypeScript and how to integrate it into both vanilla JavaScript and React projects, you’ve also explored how it works internally, the reasons behind its creation and the real-world problems it aims to solve.</p><p>Remember, TypeScript is designed for gradual adoption. You don’t need to master every feature on day one. You can start with minimal type annotations and increase type safety as you become more comfortable with the language.</p><p>Anyway, thanks for sticking around, and hey, maybe TypeScript isn’t so scary after all!</p><p>Missed <strong>Part I</strong>? Read it <a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599"><strong>here!</strong></a></p><h4>Bonus:</h4><ul><li>Node 23 lets you run TypeScript files directly, <strong>no need to compile to JavaScript first</strong>. Just run node script.ts and you’re good to go. Node strips the types at runtime automatically. Here is the actual <a href="https://github.com/nodejs/node/pull/56350">pull request</a>.</li><li>Typescript was recently <strong>rewritten in </strong><a href="https://go.dev/"><strong>Go</strong></a>, bringing a <strong>10x performance boost</strong>. Read about it <a href="https://devblogs.microsoft.com/typescript/typescript-native-port/">here</a>.</li><li><strong>Meta created their own static type checker</strong> for JavaScript called <a href="https://github.com/facebook/flow">Flow</a>. Although it was promoted internally, and even used in React (as seen in the <a href="https://github.com/facebook/react">repository</a>), Flow never achieved widespread adoption. Over time, TypeScript’s superior tooling, developer experience, and vibrant community established it as the preferred solution for typed JavaScript.</li><li>Don’t be afraid to <strong>explore the </strong><strong>@types folder</strong>. Although it may look complex, it can help you understand how types are constructed and related. Next time you encounter a type like MouseEventHandler in VSCode, you can use <strong>Go to Definition</strong> (Cmd+Click) on the type to jump directly to the file where it’s defined.</li><li>As your project grows, <strong>organize types in separate files</strong> to avoid duplication and improve maintainability. When importing types without runtime code, it is a good practice to use the type keyword for clarity and potential performance benefits:<br>import type { User } from ‘./types/UserTypes’;</li><li>For larger projects, using path aliases helps avoid long import paths. Just <strong>avoid naming aliases </strong><strong>@types</strong> since it conflicts with the reserved node_modules/@types directory.</li></ul><h4>Sources:</h4><ul><li><a href="https://www.typescriptlang.org/docs">Official documentation</a></li><li><a href="https://github.com/microsoft/TypeScript">Official repository</a></li></ul><blockquote>I’d love to hear your thoughts! You can find me on <a href="https://www.linkedin.com/in/ignacio-gavilanes/"><strong>LinkedIn</strong></a> and <a href="https://x.com/Nacho_Gavilanes"><strong>X</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86dd5085b7eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neocoast/typescript-fundamentals-86dd5085b7eb">TypeScript Fundamentals</a> was originally published in <a href="https://medium.com/neocoast">Neocoast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Fundamentals]]></title>
            <link>https://medium.com/neocoast/typescript-fundamentals-9c25127ae599?source=rss-05d4b8fe528a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c25127ae599</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nacho Gavilanes]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 14:19:23 GMT</pubDate>
            <atom:updated>2025-07-10T22:35:22.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcsI7XPkhCsWLhg_q_APDQ.png" /></figure><h4>BEGINNER-FRIENDLY</h4><h4>Getting Started (Part 1/2)</h4><p>Nowadays JavaScript is everywhere, powering websites, mobile apps, desktop software, and games on both client and server. Its ubiquity has made it an essential tool for developers in nearly every domain, creating a universal programming ecosystem that transcends traditional platform boundaries and specializations.</p><p>JavaScript’s flexibility is one of its greatest strengths, allowing quick prototyping given its dynamic nature, but it can sometimes be its biggest weakness. Consider this code:</p><pre>const user = { name: &quot;Raul&quot; };<br>user.age.toFixed(2);</pre><p>Once deployed, this code could result in your website crashing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYSDf5aKEyX6p53gxKn0CQ.jpeg" /><figcaption>A common JavaScript runtime error: trying to access a property or method, like <strong>toFixed()</strong>, on an <strong>undefined</strong> value.</figcaption></figure><p>But with TypeScript, the same code fails <strong>instantly</strong> in your editor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uy0jkCIqVEHU_kmLqg1f0w.gif" /><figcaption>TypeScript provides <strong>instant feedback</strong> in the editor. Here, it warns us at compile time about accessing <strong>user.age</strong> on an object that might be <strong>undefined</strong>, preventing a potential runtime error.</figcaption></figure><p>TypeScript catches the mistake as you type, not after deployment.</p><p>This is TypeScript’s superpower: it brings structure to JavaScript’s flexibility, keeping your sanity intact as projects grow.</p><p>But TypeScript wasn’t built in a vacuum. Before we dive into code, let’s take a step back and look at why TypeScript was created and what problems it aimed to solve. Knowing the <em>why</em> behind TypeScript makes it easier to learn and apply with confidence.</p><p>This is the first part of a two-part series. By the end of these installments, you’ll not only be able to write basic TypeScript, but also understand why it exists and how it fits into the JavaScript ecosystem.</p><p>Now, without further ado, let’s dive in.</p><h3>JavaScript’s Backstory</h3><p>JavaScript was created in 1995 as a simple scripting language to add interactivity to otherwise static HTML pages. It was originally intended for small snippets of code embedded directly into HTML, and writing more than a few dozen lines was uncommon. At the time, it was never designed for building large-scale applications.</p><p>Over time, though, JavaScript became increasingly popular, and web developers started using it to create more complex and interactive experiences. Its versatility led to adoption beyond browsers, with the rise of server-side JavaScript through <a href="https://nodejs.org/en">Node.js</a>, first released in 2009.</p><p>Given its original purpose for small-scale scripting, JavaScript was designed as a dynamically typed language, a choice that worked well for its early goals but introduced challenges as applications grew larger.</p><h3>Statically vs Dynamically Typed Languages</h3><p>In statically typed languages like C, C++, and Java, you explicitly define variable types. The compiler checks for type-related errors before the program runs, catching mistakes early, like trying to access a property that doesn’t exist on an object.</p><p>Dynamically typed languages like JavaScript, by contrast, don’t enforce types at compile time. Variables can hold any value, and many mistakes go unnoticed until runtime, leading to unexpected errors. We saw an example of this earlier: trying to call .toFixed() on a missing age property caused a runtime error that could crash the application.</p><p>This kind of flexibility is useful for small scripts and quick iterations. But as codebases grow larger, the lack of type safety makes maintenance harder. Bugs slip through until runtime, and refactoring becomes risky and error-prone.</p><p>These growing pains are exactly what TypeScript was created to address. It introduces <em>optional</em> static typing, improves tooling, and makes JavaScript development safer without sacrificing the flexibility that made it so popular in the first place.</p><p>The next couple of sections provide valuable context that will make the core concepts easier to understand. However, if you’d prefer to jump straight into the syntax, you can skip ahead to the <strong>Basic Concepts</strong> section.</p><h3>TypeScript’s Arrival</h3><p>The 2010s saw an explosion of JavaScript frameworks. Tools like AngularJS, Ember.js, and React enabled developers to build increasingly structured and interactive web applications. Combined with the rise of Node.js, JavaScript evolved from a browser-only scripting language into a language powering full-stack development.</p><p>But as applications grew more complex, JavaScript’s dynamic nature became a liability. The lack of type safety made refactoring risky, tooling was limited, and runtime errors often slipped through the cracks.</p><p>For example, consider a common refactor:</p><pre>// Before refactor: property is named &#39;email&#39;<br>function sendEmail(user) {<br> return user.email.toLowerCase();<br>}<br><br>// After refactor: &#39;email&#39; renamed to &#39;emailAddress&#39; in user model, but<br>// this function wasn&#39;t updated. No compile error, but crashes at runtime.<br>function sendEmail(user) {<br> return user.email.toLowerCase(); // Runtime error<br>}</pre><p>JavaScript won’t warn you, it assumes you know what you’re doing. A typo or stale property access might only surface in production. With TypeScript, this kind of issue is caught immediately by the type checker, making large-scale changes safer and faster.</p><p>Microsoft had already explored solutions to these challenges. In the mid-2000s, they experimented with <a href="https://github.com/nikhilk/scriptsharp">Script#</a>, a project by Nikhil Kothari that compiled C# into JavaScript. While innovative, Script# required developers to abandon JavaScript entirely and introduced significant tooling overhead, limiting its adoption. The lessons from that project, however, provided valuable insights.</p><p>Armed with that experience, Microsoft took a new approach. Led by Anders Hejlsberg, the lead architect behind C#, they introduced TypeScript in 2012. Instead of replacing JavaScript, they built on top of it. As a superset, all valid JavaScript code is also valid TypeScript, enabling gradual adoption.</p><p>That compatibility proved to be TypeScript’s killer feature. Existing codebases could migrate file by file rather than being rewritten from scratch. JavaScript developers could keep writing familiar syntax and gradually introduce TypeScript’s features.</p><p>TypeScript wasn’t designed to make JavaScript statically typed. Its primary goal was to improve the developer experience. By catching bugs earlier, providing IntelliSense, enhancing code navigation, and supporting better tooling, it addressed JavaScript’s pain points without sacrificing flexibility.</p><p>A pivotal moment in TypeScript’s trajectory came in 2014 when the Angular team decided to rewrite the popular AngularJS framework using TypeScript, resulting in <a href="https://angular.dev/">Angular</a> version 2. This move was crucial in accelerating TypeScript’s widespread adoption.</p><p>Today, TypeScript is deeply integrated into modern software development. It’s supported by major frameworks like Angular, Next.js, and Vue, and used across both front-end and back-end codebases. With approximately <strong>84 million</strong> weekly downloads on <a href="https://www.npmjs.com/package/typescript">npm</a>, TypeScript has evolved from a helpful tool into an industry standard.</p><h3>How The TypeScript Compiler Works</h3><p>At the heart of TypeScript is the TypeScript Compiler (tsc). While it’s often called a compiler, it’s technically a transpiler, since it doesn’t turn code into machine instructions like C or Rust would. Instead, it converts TypeScript into plain JavaScript that browsers and Node.js can understand.</p><p>Here’s what happens under the hood when you run tsc:</p><h4><strong>1. Type Checking</strong></h4><p>First, TypeScript checks your code for type errors. It compares your code against the types you’ve defined (or that it has inferred) and surfaces any mismatches, like trying to call a method on a number that doesn’t exist.</p><h4><strong>2. Generating The Abstract Syntax Tree (AST)</strong></h4><p>Before making any changes to the code, TypeScript generates an Abstract Syntax Tree (AST). This is an in-memory representation of the code’s structure, where the code is parsed and broken down into nodes that represent various language constructs, such as variables, functions, or expressions.</p><p>To help visualize what an AST looks like, I used a VSCode extension that lets you explore the AST of a given file. Here’s an example using a random file I found:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWwS8zwwK9D6y3RIcIX2vQ.gif" /><figcaption>A live view of the Abstract Syntax Tree (AST) using the <a href="https://github.com/vscode-box/vscode-ast">vscode-ast extension</a>.</figcaption></figure><p>The AST serves two key purposes:</p><ul><li><strong>Type Checking:</strong> TypeScript uses the AST for type inference and to analyze the types in your code, comparing them to the expected types and catching errors, like calling methods on the wrong data type.</li><li><strong>Code Transformation:</strong> TypeScript also uses the AST to transform the code. These transformations include the next two steps: type stripping and transpilation.</li></ul><h4><strong>3. Stripping Type Annotations</strong></h4><p>Since JavaScript doesn’t support types, TypeScript strips out anything it added, like type annotations or interfaces. For example, let x: number becomes just let x.</p><h4><strong>4. Transpiling Modern JavaScript Features</strong></h4><p>Depending on your target option in tsconfig.json, TypeScript may convert modern JavaScript syntax (such as async/await, arrow functions, or const/let) into older JavaScript that works in legacy environments. This is similar to how <a href="https://babeljs.io/">Babel</a> helps JavaScript use cutting-edge features while ensuring compatibility with older browsers.</p><h4><strong>5. Outputting JavaScript</strong></h4><p>Finally, it writes the result to a .js or .jsx file. That output can be run in any JavaScript environment, whether it’s the browser, Node.js, or a serverless function.</p><h3>Getting started</h3><p>To start working with TypeScript, we need to install the TypeScript package, either locally or globally, using your package manager of choice. Here, we’ll install it globally with npm:</p><pre>npm install -g typescript</pre><p>The typescript package includes the TypeScript compiler (tsc), the language server (tsserver) that powers editor features like IntelliSense and autocompletion, as well as core libraries, type definitions, and compiler utilities.</p><p>Let’s create a simple script.ts file:</p><pre>console.log(&#39;Hello!&#39;);</pre><p>Now, while in the same directory as script.ts run:</p><pre>tsc script.ts</pre><p>You’ll notice that a script.js file was generated. This is the output of the TypeScript compiler. If we open the file, you’ll notice the contents are identical. That’s because the original code contains no TypeScript-specific syntax, and since TypeScript is a superset of JavaScript, valid JavaScript compiles without changes.</p><p>Let’s now add some TypeScript-specific syntax, recompile, and check the output. Don’t worry if it looks unfamiliar, we’ll break it down later:</p><pre>let sample: { a: number; b: boolean; c: string } = {<br> a: 2,<br> b: true,<br> c: &#39;this is a string&#39;,<br>};</pre><p>Run it again:</p><pre>tsc script.ts</pre><p>and open up script.js</p><pre>var sample = {<br> a: 2,<br> b: true,<br> c: &quot;this is a string&quot;,<br>};</pre><p>Notice that the type annotations are gone (tsc strips them out entirely during compilation).</p><p>Now, let’s modify our script.ts to include a type mismatch:</p><pre>let a = &#39;this is a string&#39;;<br>a = 5;<br><br>console.log(a);</pre><p>If we now run tsc script.ts, we’ll see the following error in the terminal:</p><pre>Type &#39;number&#39; is not assignable to type &#39;string&#39;.</pre><p>However, even with that error, TypeScript still emits a script.js file:</p><pre>let a = &#39;this is a string&#39;;<br>a = 5;<br><br>console.log(a);</pre><p>And running it with node script.js we’ll see it outputs 5.</p><p>Why did it compile even with an error? This is because of the nature of tsc and how it separates the type checking and compilation step.</p><p>By default, TypeScript performs type checking, then proceeds with compilation, even if it finds errors. This means it will still emit JavaScript unless you explicitly tell it not to (with the noEmitOnError flag). While you could pass flags individually through the command line, that quickly becomes cumbersome. That’s where the tsconfig.json file comes in handy.</p><h3>Configuring Your TypeScript Project With tsconfig.json</h3><p>The tsconfig.json file tells the TypeScript compiler how to process your project. It defines the root files, sets compiler options, and controls how TypeScript behaves during compilation. This configuration file is conceptually similar to JavaScript’s jsconfig.json.</p><p>While we won’t delve into every available option here (given the extensive nature of the topic), it’s worth noting that there are some essential compiler flags that can significantly improve the developer experience and help catch bugs early. Here are some of these options inside a rudimentary tsconfig.json:</p><pre>{<br> &quot;compilerOptions&quot;: {<br>   &quot;target&quot;: &quot;es6&quot;,<br>   &quot;outDir&quot;: &quot;./dist&quot;,<br>   &quot;noEmit&quot;: true,<br>   &quot;strict&quot;: true,<br>   &quot;baseUrl&quot;: &quot;./src&quot;,<br>   &quot;paths&quot;: {<br>   &quot;@components/*&quot;: [&quot;components/*&quot;],<br>   &quot;@utils/*&quot;: [&quot;utils/*&quot;]<br>   }<br> },<br> &quot;include&quot;: [&quot;src/**/*&quot;],<br> &quot;exclude&quot;: [&quot;node_modules&quot;]<br>}</pre><h4><strong>compilerOptions</strong>:</h4><p>This section contains options that control how TypeScript compiles your code.</p><ul><li><strong>target</strong>: Specifies the version of JavaScript your code will be compatible with (e.g., es6, es5). TypeScript will transpile your code to match this version.</li><li><strong>outDir</strong>: Defines the output directory where the JavaScript files generated by transpiling your .ts files will be saved. If noEmit is set to true, TypeScript will not generate any output files, so the outDir directory will remain empty.</li><li><strong>noEmit</strong>: When set to true, TypeScript will not emit JavaScript files. This option is common with modern tools like Vite or frameworks like Next.js, which use bundlers like <a href="https://esbuild.github.io/">esbuild</a> or <a href="https://swc.rs/">SWC</a> to handle transpilation and bundling. These tools are faster and more optimized for modern development workflows, and they handle the transpiling more efficiently than TypeScript’s own compiler.</li><li><strong>strict</strong>: Enables all strict type-checking options, such as strictNullChecks, noImplicitAny, and others. Enabling strict mode is considered a best practice and is highly recommended because it improves code quality and makes type checking more comprehensive and predictable.</li><li><strong>baseUrl</strong>: Specifies the base directory to resolve non-relative module names. Typically, this would be your src folder. This allows TypeScript to find files more easily.</li><li><strong>paths</strong>: Defines custom paths or aliases for easier imports.</li></ul><h4><strong>include</strong>:</h4><p>Specifies the files or directories that should be included in the compilation. By default, TypeScript will look for .ts files in the src folder.</p><h4><strong>exclude</strong>:</h4><p>Specifies the files or directories that should be excluded from the compilation. This is typically used to exclude node_modules, which often contains external dependencies and does not need to be compiled by TypeScript.</p><p>If you’re working with vanilla JavaScript and want to easily set up TypeScript for your project, you can generate a basic tsconfig.json file by running tsc --init. This will create a default configuration that you can customize to suit your needs.</p><p>By configuring your tsconfig.json file properly, you can customize the behavior of TypeScript to suit your project’s needs and integrate seamlessly with modern build systems. Enabling strict mode, defining path aliases, and configuring the other relevant flags will help ensure a more efficient, organized, and smoother development experience.</p><h3>Declaration Files</h3><p>With your tsconfig.json configured, it’s time to look at how TypeScript understands the types of external JavaScript code (like libraries or framework-specific features). This is where <strong>declaration files</strong> come into play.</p><p>Declaration files, identifiable by their .d.ts extension, act as type annotations for existing JavaScript code. They contain only type information, no executable logic. For instance, writing const x = 5; in a declaration file will throw an error, as these files are meant solely to describe types, not implement functionality. Think of them as type definitions that outline the structure of JavaScript code for TypeScript. A key feature of declaration files is that they can define global types that are accessible throughout your entire application.</p><p>When you import a JavaScript library, TypeScript can’t infer types from .js files. Declaration files fill this gap, enabling features like IntelliSense, catching mismatched argument types or missing properties.</p><p>You may be asking yourself, <em>where do these files actually show up in a codebase?</em> The answer is, they can appear in a few different places.</p><h4><strong>Frameworks and Global Types</strong>:</h4><p>Frameworks usually generate their own declaration file when scaffolding a new project. In the case of Next.js, we see a file at the root of our project called next-env.d.ts, which looks like this:</p><pre>/// &lt;reference types=&quot;next&quot; /&gt;<br>/// &lt;reference types=&quot;next/image-types/global&quot; /&gt;<br><br>// NOTE: This file should not be edited<br>// See https://nextjs.org/docs/app/api-reference/config/typescript for more information.</pre><p>The /// are called <strong>triple-slash directives</strong>, and they tell TypeScript to load types from a specific directory before your code runs. For example, Next.js extends the Fetch API with extra features like the revalidate method or tags property, among others. The directive ensures TypeScript pulls these enhanced types from node_modules/next, making them <strong>globally</strong> recognized across your project. This way, you will see them as suggestions in your code editor.</p><h4><strong>Third-Party Libraries</strong>:</h4><ul><li><strong>Libraries Written In TypeScript</strong>: Although these libraries are authored in .ts, they’re typically compiled and shipped as JavaScript. To ensure consumers still get type information, library authors emit .d.ts files alongside the compiled .js output. This is done by setting ”declaration”: true in tsconfig.json, so tsc generates both .js (executable) and .d.ts (type definition) files.<br> The ”types” field in package.json specifies the entry point for your type definitions. For example, if you set ”types”: “dist/index.d.ts”, then dist should match the outDir you configured in your tsconfig.json.</li><li><strong>JavaScript Libraries Without Type Definitions</strong>: If a JavaScript library doesn’t provide its own .d.ts files, you can add TypeScript support using community-maintained type definitions from the @types organization on npm. For example, install type definitions for <a href="https://github.com/lodash/lodash/tree/main">lodash</a> with:</li></ul><pre>npm install --save-dev @types/lodash</pre><p>In reality, most developers rarely write declaration files since modern TypeScript libraries generate them automatically, and @typespackages cover many popular JavaScript tools. But wait a minute, <em>where are all these. types definitions actually coming from</em>? <em>Who writes and maintains them?</em></p><p>To answer that, let’s take a look at the DefinitelyTyped repository.</p><h3>The DefinitelyTyped repository</h3><p>When Microsoft first released TypeScript, one of the biggest challenges was encouraging libraries to adopt it. Many popular libraries were written in plain JavaScript, and adding type support required time and effort that maintainers didn’t always have.</p><p>To address this, Microsoft created the <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a> repository, a massive, community-maintained collection of .d.ts files for third-party JavaScript libraries.</p><p>Here’s how it works:</p><ul><li>If a JavaScript library doesn’t include built-in type definitions, the community can contribute them to the DefinitelyTyped repo.</li><li>These type definitions are published under the @types scope on npm. For example, the types for react live in @types/react, and types for lodash live in @types/lodash.</li><li>When you install them via:</li></ul><pre>npm install --save-dev @types/react</pre><p>The type definitions are added to your node_modules/@types directory, making them instantly available to your project.</p><p>You can inspect this folder in node_modules/@types to see all the community-maintained type definitions currently installed in your project. This directory acts as a type bridge, connecting plain JavaScript libraries to the TypeScript compiler and your editor’s IntelliSense system.</p><p>While TypeScript doesn’t ship with all of these definitions out of the box, it’s designed to automatically include them from @types once installed. This makes your tooling behave <strong>as if the library was written in TypeScript</strong>, even if it wasn’t.</p><p>Alright, enough internals. Let’s get our hands dirty and start writing some actual TypeScript!</p><h3>Basic Concepts</h3><p>The idea for this portion of the blog is to go over the most basic concepts. In <a href="https://medium.com/p/86dd5085b7eb"><strong>Part II</strong></a>, we will go deeper into more advanced topics, but for now, the goal is to understand basic syntax and get comfortable using TypeScript’s simpler features.</p><h4>Implicit Inference</h4><p>When you write let x:number, you’re explicitly declaring x to be of type number. However, TypeScript can often <strong>infer</strong> the type of a variable even without an explicit annotation, especially:</p><ul><li>during variable initialization</li><li>when assigning default values to parameters</li><li>when determining function return types</li></ul><p>This type inference works because the TypeScript compiler builds an <strong>abstract syntax tree</strong> to analyze your code’s structure and context (just like we saw earlier when exploring how the compiler works). Inference works great in straightforward scenarios. But when TypeScript can’t confidently determine the type, say, when a variable is declared without an initializer or is assigned from an ambiguous source, it defaults to the any type. This happens unless noImplicitAny is enabled in your tsconfig.json, which would produce an error instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9kuUp_CjKDpshyBsbMoIw.gif" /><figcaption>Unassigned variables are of type <strong>any</strong> by default.</figcaption></figure><p>But what exactly is this any type anyways?</p><h4>The any Type</h4><p>The any type means anything goes. When you use it, you’re essentially opting out of TypeScript’s type system, which is ironic, since type safety is TypeScript’s main value proposition.</p><p>Technically, this is valid:</p><pre>let x: any;<br>x = 12;<br>x = true;</pre><p>Using the any type is like adding a @ts-ignore comment around every usage of the variable. The compiler won’t complain, no matter what you assign or how you use it.</p><p>Generally, you should steer clear of using any, except when you’re actively converting a JavaScript project to TypeScript. If you see any in your code, it often indicates an opportunity to define a more precise type or use a safer option like unknown (we’ll discuss this in <a href="https://medium.com/p/86dd5085b7eb"><strong>Part II</strong></a>).</p><h4>Inline Definitions</h4><p>We are now going to move quickly through some basic examples of inline type definitions for some common primitives.</p><p><strong>Variables:</strong></p><pre>let isActive: boolean = true;<br>let age: number = 30;<br>let userName: string = &quot;John&quot;;</pre><p>TypeScript allows you to explicitly annotate the types of your variables. In these cases, the types are straightforward: boolean, number, and string.</p><p><strong>Arrays:</strong></p><pre>let numbers: number[] = [1, 2, 3]; // Bracket syntax<br>let otherArray: Array&lt;number&gt; = [1, 2, 3]; // Generic array syntax</pre><p>Both of these declare an array of numbers. Choose whichever style you prefer, bracket syntax is more common, but the generic form is equally valid.</p><p><strong>Functions:</strong></p><pre>function greet(name: string): string {<br> return `Hello, ${name}!`;<br>}</pre><p>This function takes a string and returns a string.</p><pre>const func = (a: string, b: string): void =&gt; {<br> // do something<br>};</pre><p>The return type here is void, which means the function doesn’t return anything. It’s commonly used for functions that perform side effects, like DOM manipulation.</p><pre>const func = ({ a, b }: { a: string; b: number }): void =&gt; {<br> // Do something<br>};</pre><p>You can also type destructured parameters directly, this function expects an object with a string and a number.</p><pre>// Using a tuple as function parameter<br>// Tuples are fixed-length, ordered, array-like types<br>const func = (padding: [number, number, number, number]): void =&gt; {<br> // Do something<br>};</pre><p>This function expects a tuple of exactly four numbers, for example, it could represent padding in clockwise order: [top, right, bottom, left].</p><pre>// Async function:<br>async function getFavoriteNumber(): Promise&lt;number&gt; {<br> return 26;<br>}</pre><p>With async functions, make sure to annotate the return type as Promise&lt;T&gt; to clarify what the function resolves to. While TypeScript can often infer this, adding the return type makes your intent clearer.</p><p>Inline type definitions are totally fine for small or simple structures. In fact, they’re a great way to get started quickly. But once your types get more complex (especially when reused), it’s better to extract them into a type or interface for clarity and maintainability. We’ll dive into those next.</p><h4>Defining Types With interface and type</h4><p>TypeScript provides two main ways to define custom types: interface and type. They’re very similar, but there’s a key difference: interfaces can only describe the shape of objects, while types can represent a wider variety of structures, like unions or intersections. In order to show you how they work, let’s imagine a simple logBook function that receives a book as a parameter.</p><pre>// Using an interface<br>interface Book {<br> title: string;<br> pages: number;<br> read(): void;<br>}<br><br>function logBook(book: Book): void {<br> console.log(`${book.title} has ${book.pages} pages.`);<br> book.read();<br>}</pre><p>Here, Book is an interface describing the shape of a book object. We could alternatively use a type alias like this:</p><pre>// Using a type alias for the same object shape<br>type Book = {<br> title: string;<br> pages: number;<br> read(): void;<br>};</pre><p>Both interface and type can describe object shapes like this. However, type aliases can also represent other kinds of types that interfaces cannot. For example, unions (which we’ll discuss later):</p><pre>// Type alias describing a union type<br>type ID = string | number;</pre><p>Notice the following conventions:</p><ul><li>Both interface and type aliases use PascalCase and names are singular.</li><li>In TypeScript, each property is separated with semicolons (;) instead of commas (,), which is the case in regular JavaScript objects. While commas are technically allowed, semicolons are the preferred convention.</li></ul><p>An advantage of using type and interface over inline declarations is that the error messages are often more concise, as TypeScript will only show the name of the type or interface (like Book) instead of the full inline declaration.</p><p>Another advantage of using named types like type or interface is that they can be extracted into separate files and imported as necessary. This promotes reusability, since types may come up again and again within a codebase.</p><p>Both interface and type let you define and reuse custom shapes, and you can build on top of them similarly. Since type can represent a wider range of values (including primitives, unions, and intersections), we’ll use type throughout the rest of the blog.</p><h4>Optional And Default Parameters</h4><p>It’s common to have optional function parameters or default values for them. TypeScript supports this with the ? modifier and standard default syntax:</p><pre>function greet(name?: string, age: number = 25): string {<br> return `Hello, ${name ?? &quot;Guest&quot;}! You are ${age} years old.`;<br>}</pre><p>In this case, the name is an optional argument in the greet function, and age has a default value of 25.</p><h4>Union Types</h4><p>Let’s say we’re building a small program where a user can choose a theme. You might start with something like this:</p><pre>let theme: string;<br>theme = &quot;light&quot;; // OK<br>theme = &quot;refrigerator&quot;; // Also OK… but probably not what we want</pre><p><em>The problem</em>? Using string is too broad, it allows <strong>any</strong> value as long as it is a string. To fix this, we can use <strong>union types</strong>:</p><pre>let theme: &quot;light&quot; | &quot;dark&quot; | &quot;system&quot;;</pre><p>Now, theme is limited to just these three values. If we try assigning &quot;refrigerator”, TypeScript will show an error.</p><p>Unions aren’t just for literal strings, they’re also handy when a variable can be one of several types:</p><pre>let id: string | number;</pre><p>This means id can be either a string or a number. Super useful for APIs that might return different formats for the same field, for instance, an API that returns an ID as either &quot;42” or 42.</p><h3>Conclusion</h3><p>TypeScript transforms JavaScript’s flexibility and dynamic nature into a more robust, predictable experience, catching errors before they reach production, enhancing your editor’s tooling, and giving you the confidence to refactor and scale large codebases. In <strong>Part I</strong>, we covered TypeScript’s origins, how the compiler works, basic configuration, and core language features.</p><p>In the next installment, we’ll dive deeper into more advanced topics like utility types, operators and modifiers, TypeScript with React, and generics.</p><p>Thank you for following along, see you in <a href="https://medium.com/p/86dd5085b7eb"><strong>Part II</strong></a>!</p><h4>Bonus</h4><ul><li>Highly recommend <a href="https://www.offerzen.com/community/typescript-origins-documentary"><strong>this documentary</strong></a> if you are interested in learning more about the story of TypeScript and how it came to be.</li><li><strong>Did you know?</strong> Visual Studio Code (2015) was built using TypeScript and originally focused exclusively on JavaScript/TypeScript. By integrating TypeScript’s tsserver engine, it delivered groundbreaking features like IntelliSense and real-time error checking for JavaScript and TypeScript.<br>Before 2016, editors like Eclipse or Sublime Text required fragmented, language-specific plugins for basic tooling. Microsoft’s breakthrough came when they generalized tsserver’s success into the <a href="https://code.visualstudio.com/blogs/2016/06/27/common-language-protocol"><strong>Language Server Protocol (LSP)</strong></a>. Released in 2016, LSP allowed <strong>any language</strong> to plug in its own “language server”, decoupling editor features from hardcoded syntax rules.<br>This turned VS Code, and eventually editors like Neovim and JetBrains, into universal tools. TypeScript didn’t just improve JavaScript; it redefined how <strong>all</strong> languages interact with code editors.</li></ul><h4>Sources</h4><ul><li><a href="https://www.typescriptlang.org/docs">Official documentation</a></li><li><a href="https://github.com/microsoft/TypeScript">Official repository</a></li><li><a href="https://deno.com/blog/history-of-javascript">History of JavaScript blog</a></li></ul><blockquote>I’d love to hear your thoughts! You can find me on <a href="https://www.linkedin.com/in/ignacio-gavilanes/"><strong>LinkedIn</strong></a> and <a href="https://x.com/Nacho_Gavilanes"><strong>X</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c25127ae599" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neocoast/typescript-fundamentals-9c25127ae599">TypeScript Fundamentals</a> was originally published in <a href="https://medium.com/neocoast">Neocoast</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>