Home > Net >  Is there a way to use types from a sequelize model in typescript?
Is there a way to use types from a sequelize model in typescript?

Time:06-10

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:

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

CodePudding user response:

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

  • Related