TypeScript and the Database: Who Owns the Types?

Rate this content
Bookmark

We all love writing types in TypeScript, but we often find ourselves having to write types in another language as well: SQL. This talk will present the choose-your-own-adventure story that you face when combining TypeScript and SQL and will walk you through the tradeoffs between the various options. Combined poorly, TypeScript and SQL can be duplicative and a source of headaches, but done well they can complement one another by addressing each other's weaknesses.

FAQ

The app's database includes information about books, authors, and book reviews. It stores details like book ID, title, publication year, and content, which can be null if the publication year is unknown.

The app connects to the database, runs SQL queries to fetch data, and renders the results. It uses TypeScript to define interfaces for the data structure, ensuring type safety and accuracy in data handling.

ORM stands for Object Relational Mapper. In the app, TypeORM is used as an ORM to map database tables to JavaScript objects. This allows the app to interact with the database using high-level entity objects instead of raw SQL queries.

Issues can arise if the database schema and TypeScript types are not in sync, such as when a database column becomes nullable but the change is not reflected in TypeScript, leading to potential type errors.

The app can use ORMs or schema generators to synchronize changes. For example, using TypeORM or a schema generator like pg2ts ensures that any changes in the database schema are accurately reflected in TypeScript types.

Migrations in the app are used to apply changes to the database schema, such as altering columns or making them nullable. These migrations help maintain the database structure and ensure it aligns with the application's requirements.

Using a query builder like connects JS provides type safety for database queries, ensuring that the queries match the database schema. It simplifies writing SQL queries by allowing developers to use a more abstract syntax that integrates with TypeScript.

Tools like PGTyped read SQL queries and automatically generate TypeScript types for them. This process helps maintain type accuracy across the application by ensuring that data fetched from the database matches the expected types in TypeScript.

Using an ORM simplifies database interactions and ensures type safety but can obscure the underlying SQL and affect performance. Raw SQL gives more control and may be more efficient but requires careful management of types and database synchronization.

For complex queries, it's suggested to write raw SQL to ensure optimal performance and control. Tools like PGTyped can then be used to generate accurate TypeScript types for these queries, combining flexibility with type safety.

Dan Vanderkam
Dan Vanderkam
27 min
29 Apr, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

The Talk discusses the use of TypeScript and SQL together in software development. It explores different approaches, such as using an ORM like TypeORM or a schema generator like pg2ts. Query builders like connects JS and tools like PGTyped are also discussed. The benefits and trade-offs of using TypeScript and SQL are highlighted, emphasizing the importance of finding a middle ground approach.

1. Working with a Database and Types

Short description:

I'm working on a new app with a database for books, authors, and reviews. The web server connects to the database, runs a query, and renders all the books. I encountered a bug and discovered the need for types. By defining a book interface and specifying the structure of the table, I resolved the type errors. Running a migration allowed me to handle the possibility of null values for the publication year.

So I'm working on this cool new app, so it has a database where I have books and their authors and book reviews. I've even got some data I've put in there, so I've got some of my favorite books. And I've got a cool web server here, so it connects to the database, it runs a query, and it renders all the books. So yeah, I think it's pretty good. Let's take a look.

So I think, seems like it maybe has a bug. So let's see what's going on here. Let's see. So I guess, what is the type of books? It's Any, it's query result Any, which means that book has an Any type. So maybe I should write, maybe I should use types to solve this problem, because this is TS Congress after all, so we can define a book interface. And let's look at the structure of this table. So we've got an ID, which is a string, and we've got created by, which is a string. And we've got title, which is a string, and we've got publication year. We're just gonna copy that. For the JavaScript people here, integers are a special kind of number. So let's just go number. And last but not least, we have contents, which is a string, or I think it could be null. And with the node-progress library, I believe you can specify a return type for a query. And hey, lo and behold, we have some type errors. So yeah, I think I just misspelled year. It should be publication year. So let's fix that. And now if we head over here, hey, what do you know? Pretty good. So types can definitely be useful when you're working with SQL. But it's not the full story.

So let's see what happens when you run a migration. So I realized that the publication year could actually be null if we don't know when it's published. So for example, who knows exactly when the Iliad and the Odyssey were published? So better just leave it as null. So let's run that. And we can confirm that.

2. Handling Database Schema Changes

Short description:

We encountered an issue when our data schema in the database changed, but the type we manually wrote didn't update accordingly. By making the publication year nullable, we resolved the error. TypeScript provided an error message when we attempted to subtract null, allowing us to fix the issue by adding a conditional.

Yep, we have our new books and publication year is null. So yeah, let's see what happens. Yep, null. And fun fact, in JavaScript 2022 minus null is in fact 22 because JavaScript. So the problem here is that we changed our data schema in the database, but this type that we wrote by hand didn't update to reflect that change. So really, publication year now is nullable. So it should be number or null. And once we make that change, then TypeScript gives us an error, right? So yeah, TypeScript is nice enough to say that you can't subtract null. And so I think here I have the fix here. We just add a conditional. Yeah, great. And let's see if that fixes things. Sure enough, it does. So once again, types can be very helpful, but there's also some potential problems here.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

TypeScript and React: Secrets of a Happy Marriage
React Advanced Conference 2022React Advanced Conference 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
Type-checking a TypeScript codebase can be slow, especially for monorepos containing lots of projects that each need to use the type checker to generate type declaration files. In this talk, we introduce — for the very first time — a new TypeScript feature we are working on called “Isolated Declarations” that allows DTS files to be generated without using the type checker at all! This opens the door to faster declaration generation in TypeScript itself, as well as in external tools written in other languages such as ESBuild and swc. You'll see how to use this new option, and maybe (just maybe) you’ll be convinced about the benefits of explicit return types! Most importantly, we will show how Isolated Declarations enables parallel builds to spread work across your CPU cores to significantly improve the build speed of your TypeScript projects.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.

Workshops on related topic

React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
How to Solve Real-World Problems with Remix
Remix Conf Europe 2022Remix Conf Europe 2022
195 min
How to Solve Real-World Problems with Remix
Featured Workshop
Michael Carter
Michael Carter
- Errors? How to render and log your server and client errorsa - When to return errors vs throwb - Setup logging service like Sentry, LogRocket, and Bugsnag- Forms? How to validate and handle multi-page formsa - Use zod to validate form data in your actionb - Step through multi-page forms without losing data- Stuck? How to patch bugs or missing features in Remix so you can move ona - Use patch-package to quickly fix your Remix installb - Show tool for managing multiple patches and cherry-pick open PRs- Users? How to handle multi-tenant apps with Prismaa - Determine tenant by host or by userb - Multiple database or single database/multiple schemasc - Ensures tenant data always separate from others
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Building a Hyper Fast Web Server with Deno
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Matt Landers
Will Johnston
2 authors
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.