# Type Safety and Input Validation — Prisma / TypeORM / Sequelize

Source: https://www.skillbyai.com/en/orms/or-type-safety

> Compare how far each ORM's types protect you, where they lie at runtime, and why API input still needs validation.

## What the types do and do not promise

**Prisma** generates types from the schema, and query results are typed from the query itself: if you `select` only `id` and `name`, the result type has only those fields, and if you `include` posts, `posts` appears in the type. This catches many mistakes at compile time. **TypeORM** types come from your entity classes, so `user.posts` is typed `Post[]` even when you did not load the relation; at runtime it is `undefined`, and the compiler cannot warn you. **Sequelize** in TypeScript needs extra help: helper types such as `InferAttributes`, `InferCreationAttributes` and `CreationOptional` describe model fields, and `declare` keeps class fields from shadowing Sequelize's getters. None of these types validate data coming *into* your app. A request body typed as `CreateUserInput` is still whatever JSON the client sent. Validate it at the API boundary with a schema library, and keep database constraints as the final safety net.

## Result types follow the query in Prisma

Hover over each variable in an editor: the types differ because the queries differ.

```ts
import { Prisma } from '@prisma/client';

const slim = await prisma.user.findFirst({ select: { id: true, name: true } });
// slim: { id: number; name: string } | null

const withPosts = await prisma.user.findFirst({ include: { posts: true } });
// withPosts: (User & { posts: Post[] }) | null

// Reusable type for a user loaded with posts
type UserWithPosts = Prisma.UserGetPayload<{ include: { posts: true } }>;
```

## Typed Sequelize model

`CreationOptional` marks fields the database fills in, so `User.create` does not demand them.

```ts
import { Model, DataTypes, InferAttributes, InferCreationAttributes, CreationOptional } from 'sequelize';

class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  declare id: CreationOptional<number>;
  declare email: string;
  declare name: string;
}

User.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    email: { type: DataTypes.STRING, allowNull: false, unique: true },
    name: { type: DataTypes.STRING, allowNull: false },
  },
  { sequelize, modelName: 'User' },
);
```

**Quiz:** In TypeORM, user.posts is typed Post[], but you called findOneBy({ id }) without relations. What is user.posts at runtime?

- [ ] An empty array
- [ ] A Promise that loads the posts
- [ ] All posts in the table
- [x] undefined, because the relation was not loaded

*Answer:* undefined, because the relation was not loaded. The entity type describes the shape when loaded, not what was actually fetched. Without relations (or eager: true), the property is simply not set.
