Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to pass my types from the sequelize model to the typescript?

Is there a way to pass my types from the sequelize model to the typescript?

My model code:

import { Table, Column, Model, DataType } from 'sequelize-typescript';

@Table
export class User extends Model {
    @Column({ type: DataType.UUID, defaultValue: DataType.UUIDV4 })
    userId!: string;

    @Column({ allowNull: false })
    username!: string;

    @Column({ allowNull: false, unique: true })
    email!: string;

    @Column({ defaultValue: false })
    confirmed!: boolean;

    @Column({ allowNull: false })
    password!: string;

    @Column({ defaultValue: false })
    isAdmin!: boolean;
}

Code in my route with instance fields of model, they all have type any:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const { userId, username, email, confirmed, password, isAdmin } = req.body;

>Solution :

Yes, you can use the User class as a type for req.body.

const { 
  userId, 
  username, 
  email, 
  confirmed, 
  password, 
  isAdmin
} = req.body as User

Playground


You should be a bit careful with the User type, as it includes a lot of extra functions like $count() or $create(). You should exclude them from the type when using it to type user input.

type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>

const { 
  userId, 
  username, 
  email, 
  confirmed, 
  password, 
  isAdmin
} = req.body as NonFunctionProperties<User>

Playground


If you only want the properties you defined inside the User class without any inherited properties from Model, use this:

type WithoutModel<T> = Omit<T, keyof Model>

const { 
  userId, 
  username, 
  email, 
  confirmed, 
  password, 
  isAdmin
} = req.body as WithoutModel<User>

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading