Advertisement
nodejsdeveloperskh

handle multiple type and check if there is key inside that object in typescript

Nov 27th, 2021
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export interface UserDocument {
  2.     _id: Types.ObjectId;
  3.     phoneNumber: string;
  4.     username: string;
  5.     password: string;
  6.     family: string;
  7.     name: string;
  8.     gender: GenderEnum;
  9.     createdAt?: Date | any;
  10.     updatedAt?: Date | any;
  11. }
  12. export interface CommentDocument {
  13.     _id?: string;
  14.     owner?: string | ObjectId | User;
  15.     title?: string;
  16.     text: string;
  17.     isVerified?: boolean;
  18.     createdAt?: Date;
  19.     updatedAt?: Date;
  20. }
  21.  
  22. function isUser(user: any): user is User {
  23.     return 'phoneNumber' in user;
  24. }
  25.  
  26. export class CommentOutputDto {
  27.     constructor(data: CommentDocument) {
  28.         this._id = data._id?.toString();
  29.         if (isUser(data.owner)) {
  30.             this.owner = {
  31.                 _id: data.owner._id.toString(),
  32.                 name: data.owner.name,
  33.                 lastname: data.owner.lastname,
  34.             };
  35.         }
  36.         /* ... */
  37.     }
  38.     _id: string;
  39.    
  40.     owner?: Partial<User>;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement