类型缺少以下属性

时间:2019-04-22 07:41:29

标签: typescript typeorm

我需要一些帮助。我使用typeorm创建了User实体,我想覆盖toResponseObject 在客户类的更改返回属性中,但是当我写完后,错误发生为“类型'{userName:string; firstName:string; lastName:string; email:string; address:Address; token:string;}'缺少以下内容“用户”类型的属性:密码,hasPassword,toResponObject,comparePassword”,我想这意味着我应该返回所有用户属性,但我不想返回所有属性。我该怎么办?

user.entity.ts

import {PrimaryColumn, Column, BeforeInsert} from "typeorm";
import * as bcrypt from 'bcryptjs'
import * as jwt from 'jsonwebtoken'

export abstract class User {

    @PrimaryColumn()
    userName: string;

    @Column()
    password: string;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    email: string;

    @BeforeInsert()
    async hasPassword(){
        this.password = await bcrypt.hash(this.password,10)
    }

    async toResponObject(showToken:boolean = true){
        const {userName,firstName,lastName,email,token} = this
        const responseObject = {userName,firstName,lastName,email,token}
        if(showToken){
            responseObject.token = token
        }
        return responseObject
    }

    async comparePassword(attemp:string){
        return await bcrypt.compare(attemp,this.password)
    }

    protected get token(){
        const {userName,password} = this
        return jwt.sign({userName,password},process.env.SECRETKEY,{expiresIn:'7d'})
    }
}

customer.entity.ts

import { Pet } from "../pet/pet.entity";
import { Address } from "../address/address.entity";
import { Order } from "../order/order.entity";
import { Feedback } from "../feedback/feedback.entity";
import { User } from "../user/user.entity";
import { Entity, Column, ManyToOne, OneToMany } from "typeorm";

@Entity()
export class Customer extends User {

    @Column()
    phoneNumber: string;

    @OneToMany(type => Pet,pet => pet.owner)
    pets: Pet[];

    @ManyToOne(type => Address)
    address: Address;

    @OneToMany(type => Order,order => order.customer)
    orders: Order[];

    @OneToMany(type => Feedback,feedbacks => feedbacks.customer)
    feedbacks: Feedback[];

    async toResponObject(showToken:boolean = true):Promise<User>{
        const {userName,firstName,lastName,email,address,token} = this
        const responseObject = {userName,firstName,lastName,email,address,token}
        if(showToken){
            responseObject.token = token
        }
        return responseObject  // error ocuurs at this line
    }

}

1 个答案:

答案 0 :(得分:0)

伴随有危险的评论,您可以使用

返回用户的部分内容
async toResponObject(showToken:boolean = true):Promise<Partial<User>> {
  //...
}

这样,您无需定义新对象,仍然可以获取所需的输出。