puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

06. Generics with Class as Parameters #29

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

Here we have an example,

  1. To define a User class in order to map the database
  2. To define a MysqlDb 'class' in order to operate the database
  3. To pass the User class into MysqlDb as parameters
class User{
   username: string | undefined;
   password: string | undefined;
}

class MysqlDb{
   add(user: User): boolean{
       console.log(user);
       return true;
   }
}

var u = new User( );
u.username = 'shawn';
u.password = 1234;

var Db = new MysqlDb ( );
Db.add(u);    //  password: 1234, username: 'shawn'

If above case we would like to apply with other class, then MysqlDb would need to redefine again, therefore, here it is easier if we use Generic , then we could define different User class, but only with one MysqlDb class would be enough for managing all the data.

class MysqlDb <T>{
   add(info: T): boolean{
       console.log(info);
       return true;
   }
}

Notice here when the Db is defined, User needs to be put as a constrain, in order better using MysqlDb, otherwise, any type of Data would be able to pass into the MysqlDb.

class User{
   username: string | undefined;
   password: string | undefined;
}

var u = new User( );
                                                   // 1. method  to add data
u.username = 'shawn';
u.password = 1234;

var Db = new MysqlDb<User> ( );
Db.add(u);    //  password: 1234, username: 'shawn'

*********

class ArticleCate{
   title: string | undefined;
   desc: string | undefined;
   status: number | undefined;
                                                     // 2. method  to add data
// here using constructor to constain the instance must have these parameters.
// if any parametere does not need to be used in the instance, 
// then it should have a `?` before `:` inside the constructor definition

   constructor( params:{                     
          title: string | undefined,
          desc: string | undefined,
          status?: number | undefined,
    }){
          this.title = params.title;
          this.desc = params.desc;
          this.status = params.status;
    }
}

var a = new ArticleCate({
     title : 'This is title',
     desc: 'This is Desc',
});

var Db2 = new MysqlDb<ArticleCate>( );
Db2.add(a);