簡體   English   中英

有沒有辦法在打字稿中使用來自續集模型的類型?

[英]Is there a way to use types from a sequelize model in typescript?

有沒有辦法將我的類型從續集模型傳遞到打字稿?

我的型號代碼:

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;
}

我的路線中帶有模型實例字段的代碼,它們都具有任何類型:

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

是的,您可以使用User類作為req.body的類型。

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

操場


您應該對User類型有點小心,因為它包含許多額外的函數,如$count()$create() 在使用它來鍵入用戶輸入時,您應該將它們從類型中排除。

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>

操場


如果您想要在User類中定義的屬性而不需要從Model繼承的任何屬性,請使用以下命令:

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

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

操場

如果我正確閱讀了您的問題,Sequelize 為此提供了 Utility Type Attributes<M extends Model> https://sequelize.org/docs/v6/other-topics/typescript/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM