Logo
    Search

    TypeScript Fundamentals × Narrowing, Discriminating Unions, and Type Guards

    enMay 09, 2022

    Podcast Summary

    • Advanced TypeScript concepts and sponsorsLearn TypeScript's advanced features like type narrowing, discriminating unions, and type guards for error handling and code quality. Sentry offers a free trial for error tracking and PaymentsHub simplifies payment processing with APIs and SDKs.

      TypeScript is a powerful tool for catching errors and improving code quality, but it can sometimes be frustrating when dealing with complex types and type inference. In this Syntax episode, Wes, Barracuda, Boss, and Scott El Toro Loco discussed some advanced TypeScript concepts, including type narrowing, discriminating unions, and type guards, which can help developers better understand and manage their TypeScript code. Sentry was introduced as a sponsor and a solution for tracking and managing errors and exceptions in applications. Sentry allows developers to see all the important details about an error, including the operating system, browser, and GitHub issue, making it easier to diagnose and fix issues. Sentry offers a free trial with the code "tasty treat" for two months. A new sponsor, PaymentsHub, was also introduced. PaymentsHub offers easy-to-use APIs and SDKs for integrating payment processing into applications. This is not just limited to e-commerce websites but also extends to software and point-of-sale systems. PaymentsHub provides data analytics and offers a full fleet of APIs, making it a versatile solution for developers building applications that require payment processing.

    • Exploring PaymentHub's API set and TypeScript's type checkingPaymentHub's API set simplifies payment integrations with easy-to-use APIs and SDKs. TypeScript ensures accurate usage and reduces errors through its type checking feature.

      PaymentHub's API set is an essential tool for developers looking to build complex payment integrations, offering easy-to-use APIs and SDKs for various applications. Their developer portal provides a landing page with clear information on their product offerings, including which ones are PCI compliant. TypeScript, a popular programming language, requires developers to narrow down types to ensure accurate usage, avoiding assumptions and potential errors. This process, which includes type guards and exhaustive checks, ensures that TypeScript developers have the correct type before proceeding with their code. PaymentHub, a new sponsor of the podcast, offers a comprehensive solution for payment integrations, while TypeScript's focus on type checking adds an extra layer of security and precision to the development process.

    • Type Narrowing in TypeScriptTypeScript's type system requires developers to ensure correct methods are used for data types. Type narrowing converts a variable's type to a more specific one to apply appropriate methods. Essential for generic types and functions accepting multiple types.

      TypeScript's type system requires developers to ensure that they're using appropriate methods for their data types to avoid errors. Type narrowing is a technique used to ensure that the correct method is applied to a variable based on its type. For instance, if a string method is required but the variable is of a number type, type narrowing is used to convert the number to a string. This prevents errors like "Type X is not assignable to Type Y." The most common scenario where type narrowing is necessary is when dealing with generic types or functions that can accept multiple types. For example, a function that accepts a food item, which could be a sandwich or a pizza, needs to check if the food is toastable before attempting to toast it. Type narrowing can be implemented by checking the type of the variable in a conditional statement or converting the data type as needed. This technique is crucial for avoiding runtime errors and ensuring that the correct operations are performed on the data. It's important to note that type narrowing should be used judiciously, as overuse can lead to complex and difficult-to-understand code.

    • Checking data types in TypeScriptExplicitly check data types using 'in' or 'instanceof' to ensure correct methods are applied, rather than relying on 'typeof' for custom types or objects.

      When working with dynamic data in TypeScript, it's essential to add explicit checks to ensure the correct data type is being used before applying specific methods. The use of an "if statement" with the "typeof" operator to check if a variable is a string is a common approach. However, this method doesn't work with custom TypeScript types or objects. Instead, checking for specific properties using "in" or "instanceof" can help narrow down the data type and ensure the correct methods are applied. For instance, checking if an object has a specific property like "mp3" can help determine if it's a podcast or audio file. Additionally, using "instanceof" can help determine if an object is an instance of a specific class, such as "Date," which can provide access to specific methods that are not available for other data types. Overall, adding explicit checks to ensure the correct data type is being used before applying specific methods can help prevent errors and ensure the correct functionality in TypeScript.

    • TypeScript's Type Assertions and Custom Type GuardsTypeScript's assertions and type guards help ensure type safety and improve code readability by allowing developers to explicitly define types and create reusable type checks.

      TypeScript offers various techniques to help developers ensure type safety and improve code readability. Two such techniques discussed were type assertions and custom type guards. Type assertions allow developers to tell TypeScript the type of a variable, while custom type guards are functions that return whether a given value is of a certain type. These functions can be defined with the syntax `is X(value: any): value is X`, and the return type is `X` instead of a boolean. This strategy can make the code more reusable and easier to read, as complex type checks can be abstracted away into separate functions. Additionally, TypeScript offers type narrowing, which allows the type of a variable to be refined based on conditions. These techniques can be particularly useful in object-oriented programming and when working with complex types in React or other frameworks.

    • Advanced TypeScript features for precise type checkingTypeScript's advanced features like method return types, constructor types, type narrowing, and discriminating unions help developers gain better control over their codebase by enabling more precise type checking and reducing errors.

      TypeScript's type system offers advanced features like method return types, constructor types, type narrowing, and discriminating unions to help developers gain better control over their codebase. These features enable more precise type checking and can lead to fewer errors. For instance, specifying a return type for a method in a class or interface can narrow the target object's type during execution. Similarly, constructor types can help clarify the types of objects being created. Type narrowing and discriminating unions are useful when dealing with unions, allowing developers to check for specific types and properties within those unions. By using these features, developers can shift the power dynamic from TypeScript dictating the types to the developers explicitly defining them. However, it's essential to understand that these concepts might not be frequently used for everyone, especially for those not deeply involved in object-oriented programming. Nonetheless, they can prove invaluable when dealing with complex types and systems.

    • TypeScript's strictness can be frustrating, but it's there to prevent issuesTypeScript's strict type checking helps prevent bugs and improve code quality, despite potential frustrations

      TypeScript may seem annoying at times with its strict type checking and error messages, but it's actually there to prevent potential issues and save developers from future headaches. These errors are often due to mismanaged types or functions, not a fault of TypeScript itself. It's important for new TypeScript users to learn how to address these issues and not be discouraged when they encounter them. Remember, TypeScript is not wrong; it's the developer who might be. If you're stuck on an error, consider seeking advice from others or reevaluating your approach to the problem. TypeScript's strictness is ultimately a benefit that can help prevent bugs and improve code quality.

    Recent Episodes from Syntax - Tasty Web Development Treats

    790: State of JS 2023 Reactions

    790: State of JS 2023 Reactions

    Scott and Wes dive into the 2023 State of JavaScript survey, breaking down the latest trends and pain points in front-end frameworks, build tools, and JavaScript runtimes. Tune in for their hot takes and insights on what’s shaping the JavaScript landscape this year!

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    789: Do More With AI - LLMs With Big Token Counts

    789: Do More With AI - LLMs With Big Token Counts

    Join Scott and CJ as they dive into the fascinating world of AI, exploring topics from LLM token sizes and context windows to understanding input length. They discuss practical use cases and share insights on how web developers can leverage larger token counts to maximize the potential of AI and LLMs.

    Show Notes

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    CJ: X Instagram YouTube TwitchTV

    Randy: X Instagram YouTube Threads

    788: Supabase: Open Source Firebase for Fullstack JS Apps

    788: Supabase: Open Source Firebase for Fullstack JS Apps

    Scott and CJ chat with Paul Copplestone, CEO and co-founder of Supabase, about the journey of building an open source alternative to Firebase. Learn about the tech stack, the story behind their excellent documentation, and how Supabase balances business goals with open-source values.

    Show Notes

    • 00:00 Welcome to Syntax!
    • 00:30 Who is Paul Copplestone?
    • 01:17 Why ‘Supa’ and not ‘Super’?
    • 02:26 How did Supabase start?
    • 08:42 Simplicity in design.
    • 10:32 How do you take Supabase one step beyond the competition?
    • 12:35 How do you decide which libraries are officially supported vs community maintained?
      • 15:17 You don’t need a client library!
    • 16:48 Edge functions for server-side functionality.
    • 18:51 The genesis of pgvector.
    • 20:59 The product strategy.
    • 22:25 What’s the story behind Supabase’s awesome docs?
    • 25:26 The tech behind Supabase.
    • 35:46 How do you balance business goals with open source?
    • 42:01 What’s next for Supabase?
    • 44:15 Supabase’s GA + new features.
    • 48:24 Who runs the X account?
    • 50:39 Sick Picks + Shameless Plugs.

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    CJ: X Instagram YouTube TwitchTV

    Randy: X Instagram YouTube Threads

    787: You Should Try Vue.js

    787: You Should Try Vue.js

    Scott and CJ dive deep into the world of Vue.js, exploring what makes this frontend framework unique and why it stands out from React and Svelte. CJ gives a comprehensive tour, covering everything from getting started to advanced features like state management and Vue’s built-in styles.

    Show Notes

    Vue.js: The Documentary.

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    786: What Open Source license should you use?

    786: What Open Source license should you use?

    Scott and CJ dive into the world of open source, breaking down its meaning, benefits, and the various types of licenses you’ll encounter. From permissive licenses like MIT and Apache 2.0 to copy-left licenses such as GNU GPLv3, they’ll help you choose and apply the right license for your project.

    Show Notes

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    785: What’s Next for NextJS with Tim Neutkens

    785: What’s Next for NextJS with Tim Neutkens

    Scott and Wes dive into the world of Next.js with special guest Tim Neutkens from Vercel. They explore the latest updates, including the React Compiler and React Server Components, discussing their impact on developer workflows and the future of Next.js development.

    Show Notes

    • 00:00 Welcome to Syntax!
    • 00:30 What does the React Compiler do?
    • 05:04 Will React Compiler help with managing Context?
    • 06:39 What happens if you’re not using a React Compiler?
    • 09:30 Will this work on any NextJS version?
    • 12:18 What are React Server Components?
    • 16:28 Shipping all the data inside an encapsulated component.
    • 20:17 Clearing up the frustrations around retrofitting server components.
    • 23:13 Handing migration.
    • 28:30 Is this just a fetch request with props?
    • 36:41 How closely are the NextJS and React teams working?
    • 41:53 Will we ever get Async Client Components?
    • 43:52 Async Local Storage API.
    • 45:31 Turbopack.
    • 57:51 Sick Picks & Shameless Plugs.

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    784: Logging × Blogging × Testing × Freelancing

    784: Logging × Blogging × Testing × Freelancing

    In this Potluck episode, Scott and Wes tackle listener questions on modern blogging, website environmental impact, and using LangChain with LLMs. They also cover CSS hyphens, unit vs. integration testing, and balancing web development with new parenthood.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    783: How We Built a Netflix Style “Save for Offline” Feature Into Syntax

    783: How We Built a Netflix Style “Save for Offline” Feature Into Syntax

    Scott and Wes dive into the world of browser caching for audio files, exploring the File System API and the Cache API. They discuss size restrictions across different browsers, how tools like Riverside.fm leverage IndexedDB, and walk through code examples for creating, retrieving, and managing cached audio data.

    Show Notes

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott:X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    782: The Developer’s Guide To Fonts with Stephen Nixon

    782: The Developer’s Guide To Fonts with Stephen Nixon

    Scott and CJ are joined by Stephen Nixon of ArrowType to delve into the world of fonts and type for developers. They explore the intricacies of font creation, the utility of variable fonts, and offer tips for making visually appealing typography on the web.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott:X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    781: Potluck - The Value of TypeScript × Vue vs Svelte × Leetcode

    781: Potluck - The Value of TypeScript × Vue vs Svelte × Leetcode

    In this potluck episode of Syntax, Scott and CJ serve up a variety of community questions, from the nuances of beginner vs. advanced TypeScript to the pros and cons of SvelteKit. They also discuss falling out of love with React, shipping private packages via NPM, and the eternal struggle of always starting but never finishing projects.

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott:X Instagram Tiktok LinkedIn Threads

    Randy: X Instagram YouTube Threads

    Related Episodes

    Async + Await

    Async + Await

    Freshbooks — Sponsor

    If you are a small business or freelancer check out Freshbooks.com Cloud Accountingand get 30 days free. Make sure to enter SYNTAX into the "How did you hear about us" section.

    Show Notes

    02:55

    06:00

    • Callback Hell
    • Q
    • Bluebird
    • What is a promise?
    • Promises are an IOU

    8:30

    • Async + Await IS promises
    • What is Async + Await?
    • How does the code look?
    • Returning values from an await

    15:20

    • Performance Considerations
    • MEGA PROMISES
    • Promise.all()
    • Here is an example:
    • const [weather, store] = Promise.all(getWeather(), getStores());

    19:22

    22:48

    27:00

    • Snackisodes
    • Snack Packs
    • Hasty Treats?!!!

    28:00

    30:00

    • Error Handling Methods
    • View my slides for some code examples.
    • Try/Catch
    • High Order Function
    • Just handle the error when you callIt().catch(dealWithIt);
    • Node's process.on('unhandledRejection') event

    36:00

    • Browser Support
    • Babel it!

    38:00

    SIIIIICK PICKS

    42:00

    47:00

    • Sick Tip
    • Chrome's Autoplay is changing
    • Details on this
    • Visit chrome://media-engagement to see your scores

    Shameless Plugs

    Tweet us your tasty treats!

    Types in JS?

    Types in JS?

    In this Hasty Treat, Scott and Wes talk about a proposal for type syntax in JavaScript.

    Linode - Sponsor

    Whether you’re working on a personal project or managing enterprise infrastructure, you deserve simple, affordable, and accessible cloud computing solutions that allow you to take your project to the next level. Simplify your cloud infrastructure with Linode’s Linux virtual machines and develop, deploy, and scale your modern applications faster and easier. Get started on Linode today with a $100 in free credit for listeners of Syntax. You can find all the details at linode.com/syntax. Linode has 11 global data centers and provides 24/7/365 human support with no tiers or hand-offs regardless of your plan size. In addition to shared and dedicated compute instances, you can use your $100 in credit on S3-compatible object storage, Managed Kubernetes, and more. Visit linode.com/syntax and click on the “Create Free Account” button to get started.

    Sentry - Sponsor

    If you want to know what’s happening with your code, track errors and monitor performance with Sentry. Sentry’s Application Monitoring platform helps developers see performance issues, fix errors faster, and optimize their code health. Cut your time on error resolution from hours to minutes. It works with any language and integrates with dozens of other services. Syntax listeners new to Sentry can get two months for free by visiting Sentry.io and using the coupon code TASTYTREAT during sign up.

    Show Notes

    Tweet us your tasty treats

    Rust for JS Devs — Part 2

    Rust for JS Devs — Part 2

    In this episode of Syntax, Wes and Scott jump into part 2 of their look at Rust for JavaScript developers, including variables in Rust, type systems in Rust, signed and unsigned integers, and more.

    Show Notes

    let x = 5;  // x is immutable let mut x = 5; // x is mutable const MAX_POINTS: u32 = 100_000; // must be defined at compile time 
    • 10:42 Type System in Rust
    • 15:52 Types in Rust
    • 19:06 Why does Rust have signed and unsigned integers?
    • 23:35 Slicing strings with &str
    • 27:35 enum
    • 27:55 struct
    • 28:19 Vec
    • 29:33 HashMap and HashSet
    • 33:00 Converting Signed to Unsigned Numbers
    let unsigned_value: u8 = 200; let signed_value: i8 = unsigned_value as i8; 
    • 36:12 What’s up with &str?
    • 43:31 Rust error messages
    • 45:28 What is a Struct?
    struct User {    username: String,     email: String,     sign_in_count: u64,     active: bool, }  // You can create an instance of a struct like this: let user1 = User {     email: String::from("someone@example.com"),     username: String::from("someusername123"),     active: true,     sign_in_count: 1, };  impl User {     fn login(&mut self) {         self.login_count += 1;     } } 
    • 49:17 SIIIIICK ××× PIIIICKS ×××

    ××× SIIIIICK ××× PIIIICKS ×××

    Shameless Plugs

    Tweet us your tasty treats

    707: What happened in JS, CSS And Web Dev in 2023? 2023 Predictions Results!

    707: What happened in JS, CSS And Web Dev in 2023? 2023 Predictions Results!

    In this episode of Syntax, Wes and Scott review their 2023 predictions and see how they did on ideas like Deno getting hotter, new JS APIs, WASM, Houdini, CSS Container Queries, and more!

    Show Notes

    Sick Picks

    Shameless Plugs

    Hit us up on Socials!

    Syntax: X Instagram Tiktok LinkedIn Threads

    Wes: X Instagram Tiktok LinkedIn Threads

    Scott: X Instagram Tiktok LinkedIn Threads