简体   繁体   中英

Is there a way to use types from a sequelize model in 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:

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

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

Sequelize provides a Utility Type Attributes<M extends Model> for this, if I am reading your question correctly. https://sequelize.org/docs/v6/other-topics/typescript/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM