DEV Community

Arhan Khan
Arhan Khan

Posted on

TypeORM for Beginners: Type-Safe Databases in TypeScript Without Raw SQL

If you have ever written raw SQL strings inside your TypeScript code, you know the pain: a typo in a column name only shows up at runtime, and refactoring a table means hunting through string literals. TypeORM fixes that by letting you describe your tables as TypeScript classes called entities, and then it generates the SQL for you.
The core idea is simple. You define an entity like this:

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;
}
Enter fullscreen mode Exit fullscreen mode

From that class, TypeORM can create the table, insert rows, and query them — all with full type checking:

const user = await userRepository.findOneBy({ email: "arhan@example.com" });
Enter fullscreen mode Exit fullscreen mode

If you rename email to emailAddress, TypeScript tells you immediately, instead of your app crashing in production.
Getting started is straightforward. Install typeorm and a driver for your database, for example pg for PostgreSQL or mysql for MySQL. Create a DataSource with your connection details, list your entities, and call initialize(). For small projects you can even use SQLite with zero setup, which makes TypeORM a good way to learn before moving to a hosted database.
TypeORM is for you if you are building a TypeScript or Node.js backend with a relational database and you want your schema, your queries, and your types to stay in sync. It works with PostgreSQL, MySQL, SQLite, and others, and it supports relations, migrations, and transactions.
But know its limits. TypeORM has a learning curve: decorators, repositories, relations, and migrations are a lot to take in at once. Its query builder can generate slow SQL if you are not careful with relations, and the project has had periods of slow maintenance. For very simple apps, a lighter query builder may be less overhead.
Start today: create a tiny project with SQLite, define one entity, and write a script that inserts three rows and reads them back. Once that works, add a second entity with a relation — that is where TypeORM starts to pay off.

Top comments (0)