Lesson 37 of 56 · Typescript
Database Access with TypeORM
Duration: 25 minutes
Install
npm i typeorm reflect-metadata sqlite3
npm i -D @types/node
Add import 'reflect-metadata'; once.
Entity definition
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id!: number;
@Column({ length: 100 })
name!: string;
@Column({ type: 'int', nullable: true })
age?: number;
}
DataSource (connection) setup
import { DataSource } from 'typeorm';
import { User } from './entity/User';
export const AppDataSource = new DataSource({
type: 'sqlite',
database: 'dev.db',
synchronize: true, // auto‑create tables (dev only)
entities: [User],
});
await AppDataSource.initialize();
Repository usage
const repo = AppDataSource.getRepository(User);
await repo.save({ name: 'Alice', age: 30 });
const all = await repo.find();