पाठ 27 / 35
Type Safety and Input Validation
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Compare how far each ORM's types protect you, where they lie at runtime, and why API input still needs validation.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
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.
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.
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' },
);त्वरित जाँच: 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
- 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.